Jul-27-2017, 03:20 PM
Thank you for the corrections. Base on the previous code, I try to add a global var to keep track of the number of time the loop is excuted. But I don't know why the g_loopCount in update_value is never increamented?
Also a dumb question the code comment, is it always better to use double quote rather than single? The tutorials I read seem to use them interchaneably.
Also a dumb question the code comment, is it always better to use double quote rather than single? The tutorials I read seem to use them interchaneably.
import serial, time #random from tkinter import * from time import sleep g_program_start_time = time.time() #new g_loopCount = 0 #Prepare GPIO import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) #disable annoying warning meassages GPIO.setup(40,GPIO.OUT) #initial is on #GPIO.output(40,GPIO.HIGH) #define all functions def read_data(): #data = "Random number {}".format(random.randint(1, 99)) data = ser.readline() #time.sleep(1) return data def relay_on(): GPIO.output(40,GPIO.HIGH) def relay_off(): GPIO.output(40,GPIO.LOW) def update_value(string_var, root_window): g_loop_count = g_loop_count + 1 # new data = read_data() string_var.set(data) g_loop_end_time = time.time() #new root_window.after(1000, updateValue, string_var, root_window) #define toggle button function def toggle(): """ use t_btn.config('text')[-1] to get the present state of the toggle button """ if t_btn.config('text')[-1] == 'ON': t_btn.config(text='OFF') relay_on() #GPIO.output(40,GPIO.LOW) else: t_btn.config(text='ON') relay_off() #GPIO.output(40,GPIO.HIGH) root = Tk() root.geometry("800x400+0+0") ser = serial.Serial('/dev/ttyUSB0', 9600) var = String_var() var.set('Gethar Sensor data.') dataLabel = Label(root, textvariable = var) dataLabel.place(x=300, y=300) g_program_start_time_Label = Label(root, text = "program start at: " + str(hash(g_program_start_time))) g_program_start_time_Label.place(x=300, y=250) loop_count_Label = Label(root, text = "loop count is: " + str(g_loop_count)) loop_count_Label.place(x=300, y=275) # Add a toggle button t_btn = Button(root, text = "On/Off", command=toggle) t_btn.place(x=380, y=350) root.after(1000, update_value, var, root) root.mainloop() #END