Search code examples
pythonswitch-statementgpioledpi

Raspberry Pi blinking LED every time button is on


I have a raspberry pi attached to toggle switches and LEDs. Each switch turns on a LED and the third switch activates it's corresponding LED as well as making another blink for 20 seconds. Currently the python script will let you switch the buttons off and on as much as you want but that last while argument only runs the first time. How can I change this to blink that third LED every time GPIO 25 has been switched on?

t_end = time.time() + 20
while(1):

    GPIO.wait_for_edge(23, GPIO.FALLING)
    print ("Phase 1 Initiated")
    sounda.play()

    GPIO.wait_for_edge(24, GPIO.FALLING)
    print ("Phase 2 Initiated")
    soundb.play()

    GPIO.wait_for_edge(25, GPIO.FALLING)
    print ("Phase 3 Initiated")
    soundc.play()
    while time.time() < t_end:
        GPIO.output(6, GPIO.HIGH) 
        sleep(.5)
        GPIO.output(6, GPIO.LOW) 
        sleep(.5) 

Solution

  • You're setting t_end to be equal to time.time() + 20 before your outer while loop, and never updating it after that, so that once 20 seconds has passed and time.time() becomes equal to and then greater than t_end, the code in your inner while time.time() < t_end while loop will never be executed again.

    Because the two sleep(.5) statements in this code

    while time.time() < t_end:
        GPIO.output(6, GPIO.HIGH) 
        sleep(.5)
        GPIO.output(6, GPIO.LOW) 
        sleep(.5)  
    

    mean that each blink cycle is taking one second due to having the LED on for a half second and off for a half second, why not just replace while time.time() < t_end: with for i in range(20): and then you get your 20 seconds of blinking without needing to deal with any extra time variable.