Menu Close

RGB LED Colour Cycle Using Button (Common Cathode LED, Pull-Up Switch) with Raspberry Pi Pico

To control a common cathode RGB LED connected to GPIO pins 18 (Red), 19 (Green), and 20 (Blue) using a push-button (pull-up configuration) connected to GPIO pin 5. Each press of the button cycles the LED through a set of colours.

Buy Basic Raspberry Pi Pico Kit

Component Quantity
Raspberry Pi Pico 1
RGB LED (Common Cathode) 1
330 ohms Resistors 1
Push Button 1
Breadboard 1
Jumper Wires As needed

Connections:

LED Pin Connect to Pico GPIO Resistor Note
Red GP18
Green GP19
Blue GP20
Cathode — Resistor 330 Ohms Common GND for LED
Button Pin Connect to
1 GP5 (Input)
2 GND
Note: The internal pull-up resistor makes GP5 HIGH by default. When pressed, it is pulled LOW.

Code:

from machine import Pin
import time

# Define RGB LED pins (common cathode – HIGH = ON)
red = Pin(18, Pin.OUT)
green = Pin(19, Pin.OUT)
blue = Pin(20, Pin.OUT)

# Button input with internal pull-up resistor
button = Pin(5, Pin.IN, Pin.PULL_UP)

# Define color sequence (R, G, B)
colors = [
    (1, 0, 0),  # Red
    (0, 1, 0),  # Green
    (0, 0, 1),  # Blue
    (1, 1, 0),  # Yellow
    (0, 1, 1),  # Cyan
    (1, 0, 1),  # Magenta
    (1, 1, 1),  # White
    (0, 0, 0)   # Off
]

color_index = 0
debounce_delay = 0.2  # seconds

def set_color(r, g, b):
    red.value(r)
    green.value(g)
    blue.value(b)

# Initial LED state
set_color(0, 0, 0)

# Main loop
while True:
    if button.value() == 0:  # Button is pressed (LOW)
        color_index = (color_index + 1) % len(colors)
        set_color(*colors[color_index])
        time.sleep(debounce_delay)  # Debounce delay
        # Wait for button to be released before next cycle
        while button.value() == 0:
            time.sleep(0.01)
    time.sleep(0.01)

Download Code:

  LED starts OFF.

 Each press of the push-button cycles through different colours:

Leave a Reply