Raspberry Pi- Using Threaded Callbacks to pause main loop

506 views Asked by At

Here's my code:

    #import the GPIO and time package
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(2, GPIO.IN, pull_up_down = GPIO.PUD_UP)
GPIO.setup(3, GPIO.OUT)
def hold(channel):
    GPIO.output(3, True)
    time.sleep(5)
    GPIO.output(3, False)

GPIO.add_event_detect(2, GPIO.FALLING, callback=hold, bouncetime=300)
try:
    while True:
        GPIO.output(3, True)
        time.sleep(1)
        GPIO.output(3, False)
        time.sleep(1)

except KeyboardInterrupt:
    GPIO.cleanup()

So, what I'm trying to do is have a light blink, but as soon as the button is pressed it immediately switches on for 5 seconds before resuming where it left off. I tried using plain event detection with if statements, but because of the sleep() function in my main loop, nothing will happen until after that time has passed, and I want it to happen immediately. My question is, is there a way to either pause the execution of the main loop (because otherwise the LED appears to blink as normal), or is there another way to implement this using event detection?

Edit: In case it wasn't clear, button is attached to pin 2, LED to pin 3

1

There are 1 answers

0
user3246167 On

Figured it out. Created a global Boolean variable within my callback function. Before the main loop turns on or off the light, it makes sure the Boolean value isn't set to true