Reputation: 1
I am trying to receive data from Arduino with a simple loop, sending data every 100 ms. I am trying to pull the same thing using Tkinter and display it on Canvas. but data is lagging. I tried queue and thread too but still, the same issue occurs. I am asking the User to enter port no. which is collected using the Enter button and pass it to the fetch_data
function
from queue import Queue
from threading import Thread
import serial
import tkinter as tk
queue = Queue()
port_no = 0
def fetch_data(queue):
global port_no
while True:
data = serial.Serial(port=F"com{port_no}", baudrate=250000)
while data.in_waiting == 0:
pass
data = data.readline()
data = str(data, "UTF-8")
queue.put(data)
# function for after loop
def display_data():
data = queue.get()
my_canvas.itemconfig(my_text, text=f"{data}")
window.after(100, display_data)
def get_data():
global port_no
port_no = comp_entry.get()
Thread(target=fetch_data, args=(queue,), daemon=True).start()
window = tk.Tk()
window.title("ISS Position")
window.config(padx=50, pady=50)
window.minsize(300, 300)
my_canvas = tk.Canvas(height=300, width=300, highlightthickness=0)
my_canvas.grid(column=0, row=0, padx=10, columnspan=2)
my_text = my_canvas.create_text(150, 150, text="Arduino data", font=("arial", 16, "bold"))
comp_entry = tk.Entry(width=6, font=("arial", 16, "bold"))
comp_entry.grid(column=0, row=1, pady=10)
comp_text = tk.Label(text="Enter Comp port", font=("arial", 16, "bold"))
comp_text.grid(column=1, row=1)
start_button = tk.Button(text="Start", command=display_data, font=("arial", 16, "bold"))
start_button.grid(column=0, row=2, pady=10)
connect_button = tk.Button(text="Enter", command=get_data, font=("arial", 16, "bold"))
connect_button.grid(column=1, row=2)
window.mainloop()
Upvotes: 0
Views: 57
Reputation: 47085
Note that queue.get()
is a blocking function if there is nothing in the queue.
Use queue.empty()
to check whether there are data in the queue before calling queue.get()
:
def display_data():
if not queue.empty():
data = queue.get()
my_canvas.itemconfig(my_text, text=data)
window.after(100, display_data)
Upvotes: 0