1

I have a function PlaySequence() which plays a sequence of 'LED on' and 'LED off'. There are two LEDs and the times when each LED must be on or off are defined. The function may look like this, but could be much longer.

  def PlaySequence():
      GPIO.output(LED1, True)
      time.sleep(5)
      GPIO.output(LED2, True)
      time.sleep(1)
      GPIO.output(LED1, False)
      time.sleep(3)
      GPIO.output(LED1, True)
      GPIO.output(LED2, True)
      time.sleep(7)
      GPIO.output(LED2, False)
      time.sleep(12)
      GPIO.output(LED1, True)
      time.sleep(2)
      ...

I want to run this sequence only while a button is pressed. When the button is released, I want the sequence to stop. If the button is pressed again, I want it to start from the beginning. First, I tried to do this:

GPIO.add_event_detect(button, GPIO.RISING, callback=PlaySequence)

The problem with this is that PlaySequence() will continue to run even when the button is released.

How can I interrupt or stop a running function when an event (like falling edge) happens?

  • You should try multi threading, as you want to stop execution of code on some event. When button is released cancel the thread. – rajesh6115 Mar 19 '17 at 1:40
2

So if I get this right, you want that function to loop while that button is pressed? You should detect the button being pressed. And while you are looping you should check whether the GPIO pin is low again. Some pseudo code

event press detected
    loop
        if gpio pin is low
            turn off all leds
            break loop

I hope this helps.

0

Possible Solution Can be like this....

  1. check periodically whether to stop

  2. start a thread on Pressed Button and Kill on Release the button (not recommended)


def PlaySequence(button):
      GPIO.output(LED1, True)
      if not GPIO.input(button):
           return
      time.sleep(5)
      GPIO.output(LED2, True)
      if not GPIO.input(button):
           return
      time.sleep(1)
      GPIO.output(LED1, False)
      if not GPIO.input(button):
           return
      time.sleep(3)
      GPIO.output(LED1, True)
      GPIO.output(LED2, True)
      if not GPIO.input(button):
           return
      time.sleep(7)
      GPIO.output(LED2, False)
      if not GPIO.input(button):
           return
      time.sleep(12)
      GPIO.output(LED1, True)
      if not GPIO.input(button):
           return
      time.sleep(2)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.