Search code examples
pythonraspberry-piraspbiangpioled

Continually blink an LED when a button is pressed on a raspberry pi?


I don't know Python, but I'm using it in a prototyping class. What I want to do is to use the GPIO pin on my RPi to light up an LED. That part I got, no problem. But now I want to add a button and have it blink when the button is pressed and continue to blink after the button is released. Like this: LED on, button pressed, LED off, Led on, LED off, LED on, stay on, stay on, LED off, Led on, LED off, LED on, stay on, stay on, forever. This is what I have:

import RPi.GPIO as GPIO
import time

def blink(pin):
    GPIO.output(11, GPIO.LOW)
    time.sleep(.2)
    GPIO.output(11, GPIO.HIGH)
    time.sleep(.2)
    GPIO.output(11, GPIO.LOW)
    time.sleep(.2)
    GPIO.output(11, GPIO.HIGH)
    time.sleep(.2)
    GPIO.output(11, GPIO.LOW)
    time.sleep(.2)
    GPIO.output(11, GPIO.HIGH)
    time.sleep(4)

def main():

    GPIO.setmode(GPIO.BOARD)

    GPIO.setup(11, GPIO.OUT)
    GPIO.setup(16, GPIO.IN)

    GPIO.output(11, GPIO.HIGH)

    while True:
        if GPIO.input(16):
            blink(11)
        else:
            pass
        time.sleep(.1)

    GPIO.cleanup()

if __name__ == "__main__":
    main()

This seem to only make it blink right after the button is pressed, but not continually.

How can I fix that?


Solution

  • Do you want anything to make it stop blinking? If not:

    blinking = False
    while True:
        if GPIO.input(16):
            blinking = True
    
        if blinking:
            blink(11)
    
        time.sleep(.1)
    

    What you had originally checks input 16 (the button state) repeatedly, and calls the blink() function once when the button is down; the next time you get to the top of the while True with input 16 not set, blink() isn't called.

    (If you have a second stop button on a different input pin, you could add another GPIO.input() check with a different number to set blinking to false.)

    Note that you are passing the output pin number, 11, to the blink function, but aren't using the passed value; to make that function more versatile you could change it to:

    def blink(pin):
        GPIO.output(pin, GPIO.LOW)
        time.sleep(.2)
        GPIO.output(pin, GPIO.HIGH)
        time.sleep(.2)
        GPIO.output(pin, GPIO.LOW)
        time.sleep(.2)
        GPIO.output(pin, GPIO.HIGH)
        time.sleep(.2)
        GPIO.output(pin, GPIO.LOW)
        time.sleep(.2)
        GPIO.output(pin, GPIO.HIGH)
        time.sleep(4)