Aug-01-2017, 01:03 AM
Hello. I just started learning Python
I wrote this code. The idea is to let the main thread to hadle the UI tasks and leave the relay control to a new thread. The relay should be on x seconds and off y sends. User can set to on/off duration wiyj the sliders. How ever the sliders never up date During runtime. I susppect I didn't do it right. Please advice. Thanks.
I wrote this code. The idea is to let the main thread to hadle the UI tasks and leave the relay control to a new thread. The relay should be on x seconds and off y sends. User can set to on/off duration wiyj the sliders. How ever the sliders never up date During runtime. I susppect I didn't do it right. Please advice. Thanks.
import serial, time, _thread #random from tkinter import * from time import sleep #Prepare GPIO import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) #disable annoying warning messages GPIO.setup(40,GPIO.OUT) #initially is on GPIO.output(40,GPIO.HIGH) g_on_slider_val = 0 g_off_slider_val = 0 # Define a function for the thread def relay_control( threadName, delay): while True: #on_time = float(g_on_slider_val) #g_slder_val is a global var #off_time = float(g_off_slider_val) relay_on() time.sleep(g_on_slider_val) relay_off() time.sleep(g_off_slider_val) ui.update_idletasks() ui.update() # Define main thread functions def read_data(): #data = "Random number {}".format(random.randint(1, 99)) #dummy data 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, ui_window): data = read_data() string_var.set(data) ui_window.after(1000, update_value, string_var, ui_window) #Slider function def get_on_slider_value(on_val): g_on_slider_val = on_val print (g_on_slider_val) def get_off_slider_value(off_val): g_off_slider_val = off_val print (g_off_slider_val) ui = Tk() ui.geometry("800x400+0+0") ui.title("Command Center") ser = serial.Serial('/dev/ttyUSB0', 9600) var = StringVar() var.set('Gather Sensor data.') #slider on_slider = Scale(ui, orient = HORIZONTAL, length = 300, width = 10, sliderlength = 60, from_ = 0, to = 100, command = get_on_slider_value) on_slider.place(x=250, y=100) off_slider = Scale(ui, orient = HORIZONTAL, length = 300, width = 10, sliderlength = 60, from_ = 0, to = 100, command = get_off_slider_value) off_slider.place(x=250, y=140) data_label = Label(ui, textvariable = var) data_label.place(x=300, y=300) ui.after(1000, update_value, var, ui) # Create a threads _thread.start_new_thread( relay_control, ("Thread-1", 2, ) ) ui.mainloop() #END