Is there a way to have the red LED turn on first upon pressing button, then have blue LED turn on and lastly green LED turn on?

  python, raspberry-pi4

I am working through some LED tasks on my raspberry pi 4. I have the following code and I am getting the output on the breadboard wrong, which mean the code is faulty. Since I set the ‘previous_button_state = 0’, this would mean only the first ‘if’ would be executed (red LED). Since the previous_button_state is assigned a 1 in that ‘if’ statement, it should not be turning the red LED on again until the code gets to the ‘elif’, where the previous_button_state is reassigned the number 0 again. Instead, all three LED keep turning on every time I press the button.

import RPi.GPIO as GPIO
import time

previous_button_state = 0

LED_PIN3 = 22
LED_PIN2 = 27
LED_PIN = 17
BUTTON_PIN = 26

GPIO.setmode(GPIO.BCM)

GPIO.setup(BUTTON_PIN, GPIO.IN)
GPIO.setup(LED_PIN, GPIO.OUT)
GPIO.setup(LED_PIN2, GPIO.OUT)
GPIO.setup(LED_PIN3, GPIO.OUT)

GPIO.output(LED_PIN, GPIO.LOW)
GPIO.output(LED_PIN2, GPIO.LOW)
GPIO.output(LED_PIN3, GPIO.LOW)

while True:
    if (GPIO.input(BUTTON_PIN) == GPIO.HIGH) and previous_button_state == 0:      
        GPIO.output(LED_PIN, GPIO.HIGH)
        GPIO.output(LED_PIN2, GPIO.LOW)
        GPIO.output(LED_PIN3, GPIO.LOW)
        previous_button_state = 1
        
    elif (GPIO.input(BUTTON_PIN) == GPIO.HIGH) and previous_button_state == 1:
        GPIO.output(LED_PIN2, GPIO.HIGH)
        GPIO.output(LED_PIN, GPIO.LOW)
        GPIO.output(LED_PIN3, GPIO.LOW)
        previous_button_state = 2
        
    elif (GPIO.input(BUTTON_PIN) == GPIO.HIGH) and previous_button_state == 2:
        GPIO.output(LED_PIN3, GPIO.HIGH)
        GPIO.output(LED_PIN2, GPIO.LOW)
        GPIO.output(LED_PIN, GPIO.LOW)
        previous_button_state = 0

    else:
        GPIO.output(LED_PIN, GPIO.LOW)
    time.sleep(0.01)


GPIO.cleanup()

enter image description hereenter image description here

Source: Python Questions

LEAVE A COMMENT