Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python3 newbie
#11
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.
Reply
#12
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Gnuradio python3 is not compatible python3 xmlrpc library How Can I Fix İt ? muratoznnnn 3 4,823 Nov-07-2019, 05:47 PM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020