clarkdv
clarkdv

Reputation: 3

Turn on 2 LEDs, then blink one forever on button press

I need help. I need my Raspberry Pi to turn on a Yellow LED and a Red LED. Then, when the Yellow button is pressed, I need the Yellow LED to start blinking forever, and for the Red LED to remain on.

Here is the code I have but it only partially works. It turns the Red LED on but the Yellow LED is off. (I thought that by setting GPIO.output(17, GPIO.HIGH) that that would turn the Yellow LED on, as it does for the Red LED, but it doesn’t.)

Pressing the Yellow button starts the Yellow LED blinking forever, which is correct behavior but I need both LEDs to be on and then the Yellow to start blinking forever on the button press.

What am I doing wrong? Thanks!

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings (False)
GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)  #Yellow button
GPIO.setup(17, GPIO.OUT)    #Yellow LED
GPIO.setup(27, GPIO.OUT)    #Red LED
GPIO.output(17, GPIO.HIGH)  #Turn Yellow LED On
GPIO.output(27, GPIO.HIGH)  #Turn Red LED On


blinking = False
while True:
    if GPIO.input(24):
        blinking = True

    if blinking:
        GPIO.output(17, GPIO.HIGH)
        time.sleep(.2)
        GPIO.output(17, GPIO.LOW)
        time.sleep(.2)

    time.sleep(.1)

Upvotes: 0

Views: 1110

Answers (1)

stuartnox
stuartnox

Reputation: 659

This should do the trick

import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings (False)
GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_DOWN)  #Yellow button
GPIO.setup(17, GPIO.OUT)    #Yellow LED
GPIO.setup(27, GPIO.OUT)    #Red LED
GPIO.output(17, GPIO.HIGH)  #Turn Yellow LED On
GPIO.output(27, GPIO.HIGH)  #Turn Red LED On


blinking = False
while True:
    if GPIO.input( 24 ):
        blinking = True

    while blinking:
        GPIO.output(17, GPIO.HIGH)
        time.sleep(.2)
        GPIO.output(17, GPIO.LOW)
        time.sleep(.2)

        time.sleep(.1)

Upvotes: 0

Related Questions