I am trying to input a signal from GPIO and I've assigned it to a counter where it will count every high signal input. However, GUI only shows '1'. I am probably confused with the loop, as the counter won't increment.
I understand that the GUI is blocking, but I don't know how to implement it.
Here is the following attempt that I have tried:
from guizero import App, Text
import RPi.GPIO as GPIO
import time
sensor = 16
global count
GPIO.setmode(GPIO.BOARD)
GPIO.setup(sensor,GPIO.IN)
app = App("Counter")
text = Text(app, text="1")
#when GPIO is high, however this only stops to 1
if GPIO.input(sensor):
print('detected')
def counter():
#add counter and change value by adding one
text.value = int(text.value) + 1
while GPIO.input(sensor):
time.sleep(0.01)
app.display()
Your main problem is you defined function counter()
but you didn't execute it inside while
-loop.
But there is different problem - most GUIs don't like loop because it blocks mainloop used by GUI to get (key/mouse/etc.) events for system, send them to widgets, update widget. But most GUIs have some method to execute function with delay and it can be used to execute code periodically without using loop.
I can't test it but it could be
from guizero import App, Text
import RPi.GPIO as GPIO
# --- functions ---
def counter():
if GPIO.input(sensor):
text.value = int(text.value) + 1
else:
text.cancel(counter) # stop this loop
#app.destroy() # exit program
# --- main ---
sensor = 16
GPIO.setmode(GPIO.BOARD)
GPIO.setup(sensor, GPIO.IN)
app = App("Counter")
text = Text(app, text="1")
text.repeat(10, counter) # Schedule call to counter() every 10ms (0.01s)
app.display()
BTW: using Google I found solution in guizero
doc: Loops and sleeping and App (see Methods
in App
).