On my Raspberry Pi using python3 I want to count pulses on an incoming I/O. To test I've put together a simple program.
import signal
import sys
import RPi.GPIO as GPIO
import time
iTP = 40
ictr=0
def signal_handler(sig, frame):
GPIO.cleanup()
print("\nOut of here!")
sys.exit(0)
def button_pressed_callback(channel):
global ictr
ictr+=1
def main():
print("Here we go!")
GPIO.setmode(GPIO.BOARD)
GPIO.setup(iTP, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.add_event_detect(iTP, GPIO.FALLING,
callback=button_pressed_callback, bouncetime=20)
signal.signal(signal.SIGINT, signal_handler)
sctr=0
ictr=1
while 1:
time.sleep(1)
print("====")
while sctr==ictr:
time.sleep(1)
print("busy")
while sctr!=ictr:
time.sleep(2)
print("Cnt={}".format(sctr))
ictr=0
sctr=0
main()
I want to collect a pulse count in the callback and then deal with the count in main()
. The pulses are in fact being collected in the callback - i.e. ictr
is incrementing as expected - but ictr
in main()
is not the reflecting this. I never get past the print("busy")
line even though ictr
is changing in the callback (verified with prints). I have tried a variety of combinations of global declarations but just can't seem to get this variable to be shared between the callback and main()
. Would greatly appreciate any help.