To create a Python Tkinter GUI that fetches many comma-separated values from a serial port and displays them we can use the pyserial
library to handle the serial communication. Below is a simple example demonstrating how to achieve this. Make sure you have both tkinter
and pyserial
installed. You can install pyserial
using pip if you haven't done so already:
The arduino code is simple modified version of available AnalogReadSerial example. In the code 4 AI channels are read and one DI channel is read. Their values are transmitted over Serial port. Note the COM port number of device and change accordingly in the code.
// the setup routine runs once when you press reset: void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); } // the loop routine runs over and over again forever: void loop() { // read the input on analog pin 0: int Val1 = analogRead(A0); int Val2 = analogRead(A1); int Val3 = analogRead(A2); int Val4 = analogRead(A3); bool state = digitalRead(8); // print out the value you read: Serial.print(Val1); Serial.print(Val2); Serial.print(Val3); Serial.print(Val4); Serial.println(state); delay(500); // delay in between reads for stability }
Below is the Python script.
import tkinter as tk
import serial
# Serial port configuration
SERIAL_PORT = 'COM3' # Change this to your serial port
BAUD_RATE = 9600
class SerialApp:
def __init__(self, master):
self.master = master
self.master.title("Serial Data Display")
# Create labels for each value
self.labels = ['Val1:', 'Val2:', 'Val3:', 'Val4:']
self.value_labels = []
# Configure font
label_font = ("Helvetica", 30, "bold")
# Create and place labels in grid
for i, label in enumerate(self.labels):
lbl = tk.Label(master, text=label, font=label_font)
lbl.grid(row=i, column=0, padx=20, pady=10)
value_lbl = tk.Label(master, text="", font=("Helvetica", 30))
value_lbl.grid(row=i, column=1, padx=20, pady=10)
self.value_labels.append(value_lbl)
# Open serial port
self.serial_port = serial.Serial(SERIAL_PORT, BAUD_RATE, timeout=1)
# Update the GUI
self.update()
def update(self):
try:
# Read data from serial port
line = self.serial_port.readline().decode('utf-8').strip()
values = line.split(',')
# Ensure we have four values
if len(values) == 4:
for value_lbl, value in zip(self.value_labels, values):
value_lbl.config(text=value)
except Exception as e:
print(f"Error: {e}")
# Schedule the next update
self.master.after(1000, self.update)
def on_closing(self):
self.serial_port.close()
self.master.destroy()
if __name__ == "__main__":
root = tk.Tk()
app = SerialApp(root)
# Handle window close event
root.protocol("WM_DELETE_WINDOW", app.on_closing)
root.mainloop()
The GUI will look as below
https://github.com/arihant122/Python-Tkinter-based-GUI-by-fetching-Serial-port-data-from-Arduino-
No comments:
Post a Comment