Python Forum

Full Version: Python3 newbie
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Actually, I didn't see the call in update_value, only the one at the bottom, but you should be ok.
I can't run the code without replacing of the serial I/O, so it's hard to see what's actually occuring.
You increment should work, you can use:
g_loop_count += 1
for that.
Oops I think I copied and pasted the wrong code. The code I meant to soon is this: However, I still couldn't figured out how to track the number of times loop is called. (if root.after(1000, update_value, var, root) is indeed a loop.
import serial, time #random
from tkinter import *
from time import sleep

g_program_start_time = time.time() 
g_loop_count = 0

#Prepare GPIO
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False) #disable annoying warning messages
GPIO.setup(40,GPIO.OUT)
#initial is on
#GPIO.output(40,GPIO.HIGH)

#define all functions
i = 0
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):
    data = read_data()
    string_var.set(data)

    
    root_window.after(1000, update_value, 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 = StringVar()
var.set('Gather Sensor data.')


data_label = Label(root, textvariable = var)
data_label.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
Pages: 1 2