Update value all the time in python interface (Arduino)Ask Question

问题:

This is the code I created for an arduino interface using python, I want the 3 variables to change all the time in my python interface. But they are not updating, it is just taking the fist values, I would like the screen to be able to update the values by itself.

How can I do it?

Arduino

void setup() {
  Serial.begin (9600);
}

void loop() {
  //Serial.print(3); 
  Serial.print(random(1,3));
  Serial.print(" ");
  Serial.print(random(3, 6));
  Serial.print(" ");
  Serial.print(random(7,9));
  Serial.print(" ");
  delay(200);
}

Python

import serial
import time
from Tkinter import *
root = Tk()
ser = serial.Serial("/dev/cu.usbmodem1411", 9600, timeout=1)
flagCharacter = 'k'

canvas = Canvas(root, width=1024, height=574)
canvas.pack()

photo = PhotoImage(file= r"rsz_fiori.gif")
label=Label(root, image=photo)
photo = PhotoImage(file= r"rsz_fiori.gif")
canvas.pack(side='top', fill='both', expand='yes')
canvas.create_image(0, 0, image=photo, anchor='nw')

def sensores(planeado, producido, alertas):
    canvas.create_text(190, 150, text=planeado, fill="gray", font="Helvetica 45 bold",tag="T1")
    canvas.create_text(333, 150, text=producido, fill="gray", font="Helvetica 45 bold",tag="T2")
    canvas.create_text(463, 150, text=alertas, fill="gray", font="Helvetica 45 bold",tag="T3")

while True:
    ser.write(flagCharacter)
    allitems=ser.readline(6)
    x, y, z = allitems.split()
    sensores(x, y, z)
    root.mainloop()

回答1:


Remove mainloop from an infinite loop -- that doesn't work the way you think it does.

The proper way to do something "all the time" is to create a function that updates everything once, and then call that function via after. It would look something like this:

def do_update():
    ser.write(flagCharacter)
    allitems=ser.readline(6)
    x, y, z = allitems.split()
    sensores(x, y, z)
    root.after(1000, do_update)

Once you call do_update once (and assuming mainloop is running) it will cause itself to be run once every 1000ms (1 second). Note that this only works if the call to ser.readline(6) doesn't block, and doesn't take more than a few hundred milliseconds.

You'll want to modify sensores -- it keeps writing new text items on top of the old. You should either delete the old values, or simply reconfigure them with new values.

标签: user-interface tkinter arduino
© 2014 TuiCode, Inc.