Jul-26-2017, 01:46 PM
Hi, I just started learning programming in Python3 on my own. I am wondering if someone be so kind to look at my code see if it make sense?
What this code does is taking sensor data from an Arduino, send data to Pi via serial
to dsplay data to the UI. the UI also has a button or two to control the relays from the Pi. I got the Label to display sensor data now. The button works fine as well. Any suggest to help me write better Pyphon code will be much appreciated.
What this code does is taking sensor data from an Arduino, send data to Pi via serial
to dsplay data to the UI. the UI also has a button or two to control the relays from the Pi. I got the Label to display sensor data now. The button works fine as well. Any suggest to help me write better Pyphon code will be much appreciated.
import serial, time #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 meassages GPIO.setup(40,GPIO.OUT) #initial is on GPIO.output(40,GPIO.HIGH) #define the rearData function def readData(): #data = "Random number {}".format(random.randint(1, 99)) data = ser.readline() #time.sleep(1) return data #define toggle buttonfunction def toggle(): ''' use t_btn.config('text')[-1] to get the present state of the toggle button ''' if t_btn.config('text')[-1] == 'True': t_btn.config(text='False') GPIO.output(40,GPIO.LOW) else: t_btn.config(text='True') GPIO.output(40,GPIO.HIGH) root = Tk() root.geometry("800x400+0+0") ser = serial.Serial('/dev/ttyUSB0', 9600) var = StringVar() var.set('hello') dataLabel = Label(root, textvariable = var) dataLabel.place(x=300, y=300) #l.pack() # Add a toggle button t_btn = Button(root, text = "On/Off", command=toggle) t_btn.place(x=380, y=350) def updateValue(string_var, root_window): data = readData() string_var.set(data) root_window.after(1000, updateValue, string_var, root_window) while True: #sleep(1) # Need this to slow the changes down #call readData() #data = readData() #print (str(data)) #var.set(data) root.after(1000, updateValue, var, root) root.mainloop()