zaro

How to Use an RGB LED with a Raspberry Pi

Published in Raspberry Pi & LEDs 6 mins read

To use an RGB LED with your Raspberry Pi, you need to connect it properly, typically with resistors, to the GPIO pins and write code to control the color output. Here's a breakdown:

Hardware Setup

  1. Identify your RGB LED Type: Determine if it's common anode (+) or common cathode (-). The longest leg usually indicates the common pin.

  2. Gather Components: You'll need:

    • RGB LED (common anode or cathode)
    • Raspberry Pi
    • Resistors (typically 220Ω, but values between 100Ω and 330Ω are common, see below)
    • Jumper wires
    • Breadboard (optional, but recommended)
  3. Resistor Values: The reference suggests specific resistor values, but it's important to understand why. Resistors limit the current to protect the LED. A lower resistance allows more current and thus a brighter LED, but too little resistance can damage the LED. A higher resistance limits the current, dimming the LED. Choose resistor values that provide adequate brightness without exceeding the LED's current limits. Typical values range from 220Ω to 330Ω, but checking the LED's datasheet is best. Note: The original data suggests different resistor values for different colors which isn't required but can be used to balance the brightness between colors.

  4. Wiring (Common Cathode Example):

    • Common Cathode:

      • Connect the longest leg (cathode/GND) of the RGB LED directly to a GND pin on the Raspberry Pi.
      • Connect each of the other three legs (Red, Green, Blue) to a GPIO pin on the Raspberry Pi through a resistor.
    • Recommended Pin Assignments (Example):

      • Red: GPIO 21 (through a 220Ω resistor)
      • Green: GPIO 20 (through a 220Ω resistor)
      • Blue: GPIO 16 (through a 220Ω resistor)
    • Common Anode:

      • Connect the longest leg (anode/VCC) of the RGB LED to a 3.3V pin on the Raspberry Pi.
      • Connect each of the other three legs (Red, Green, Blue) to a GPIO pin on the Raspberry Pi through a resistor, but this time the GPIO pin is configured to sink the current (i.e. drive LOW to turn the LED on).
    • It's crucial to connect the LED legs through resistors to protect the LED from burning out.

Software Setup

  1. Install RPi.GPIO Library: If you don't have it installed already, use the command:

    sudo apt-get update
    sudo apt-get install python3-rpi.gpio
  2. Python Code Example (Common Cathode):

    import RPi.GPIO as GPIO
    import time
    
    # Define the GPIO pins
    RED_PIN   = 21
    GREEN_PIN = 20
    BLUE_PIN  = 16
    
    # Set the GPIO numbering mode
    GPIO.setmode(GPIO.BCM)
    
    # Setup the GPIO pins as outputs
    GPIO.setup(RED_PIN,   GPIO.OUT)
    GPIO.setup(GREEN_PIN, GPIO.OUT)
    GPIO.setup(BLUE_PIN,  GPIO.OUT)
    
    # Function to set the color
    def set_color(red, green, blue):
        GPIO.output(RED_PIN,   red)
        GPIO.output(GREEN_PIN, green)
        GPIO.output(BLUE_PIN,  blue)
    
    try:
        while True:
            # Example: Red
            set_color(1, 0, 0)  # Red ON, Green OFF, Blue OFF
            time.sleep(1)
    
            # Example: Green
            set_color(0, 1, 0)  # Red OFF, Green ON, Blue OFF
            time.sleep(1)
    
            # Example: Blue
            set_color(0, 0, 1)  # Red OFF, Green OFF, Blue ON
            time.sleep(1)
    
            # Example: Yellow (Red + Green)
            set_color(1, 1, 0)  # Red ON, Green ON, Blue OFF
            time.sleep(1)
    
            # Example: Purple (Red + Blue)
            set_color(1, 0, 1)  # Red ON, Green OFF, Blue ON
            time.sleep(1)
    
            # Example: Cyan (Green + Blue)
            set_color(0, 1, 1)  # Red OFF, Green ON, Blue ON
            time.sleep(1)
    
            # Example: White (Red + Green + Blue)
            set_color(1, 1, 1)  # Red ON, Green ON, Blue ON
            time.sleep(1)
    
            # Example: Off
            set_color(0, 0, 0)  # Red OFF, Green OFF, Blue OFF
            time.sleep(1)
    
    except KeyboardInterrupt:
        GPIO.cleanup()

    Explanation:

    • Import Libraries: Import RPi.GPIO for GPIO control and time for delays.
    • Define Pins: Assign GPIO pin numbers to variables. Important: Change these if you used different pins during wiring.
    • Set GPIO Mode: GPIO.setmode(GPIO.BCM) sets the pin numbering scheme to BCM (Broadcom SOC channel) numbering.
    • Setup Pins as Outputs: Configure the assigned GPIO pins as output pins.
    • set_color() Function: This function takes three arguments (red, green, blue) representing the color components. A value of 1 turns the LED on for that color, and 0 turns it off. Note: For common anode LEDs, you will need to reverse these (1=off, 0=on).
    • try...except Block: This allows the program to exit gracefully when you press Ctrl+C. GPIO.cleanup() resets the GPIO pins to their default state.
  3. Run the Code: Save the code as a .py file (e.g., rgb_led.py) and run it from the terminal:

    sudo python3 rgb_led.py

    The RGB LED will cycle through different colors.

PWM for Color Mixing

For more control over the color, use PWM (Pulse Width Modulation). This allows you to control the brightness of each color channel, creating a wider range of colors.

import RPi.GPIO as GPIO
import time

# Define the GPIO pins
RED_PIN = 21
GREEN_PIN = 20
BLUE_PIN = 16

# Set the GPIO numbering mode
GPIO.setmode(GPIO.BCM)

# Setup the GPIO pins as outputs
GPIO.setup(RED_PIN, GPIO.OUT)
GPIO.setup(GREEN_PIN, GPIO.OUT)
GPIO.setup(BLUE_PIN, GPIO.OUT)

# Create PWM objects for each color
RED_PWM = GPIO.PWM(RED_PIN, 100)  # 100 Hz frequency
GREEN_PWM = GPIO.PWM(GREEN_PIN, 100)
BLUE_PWM = GPIO.PWM(BLUE_PIN, 100)

# Start PWM with 0% duty cycle (off)
RED_PWM.start(0)
GREEN_PWM.start(0)
BLUE_PWM.start(0)

# Function to set the color using PWM
def set_color(red, green, blue):
    RED_PWM.ChangeDutyCycle(red)
    GREEN_PWM.ChangeDutyCycle(green)
    BLUE_PWM.ChangeDutyCycle(blue)

try:
    while True:
        # Example: Fade through red
        for i in range(0, 101):
            set_color(i, 0, 0)
            time.sleep(0.01)

        # Example: Fade through green
        for i in range(0, 101):
            set_color(0, i, 0)
            time.sleep(0.01)

        # Example: Fade through blue
        for i in range(0, 101):
            set_color(0, 0, i)
            time.sleep(0.01)

except KeyboardInterrupt:
    RED_PWM.stop()
    GREEN_PWM.stop()
    BLUE_PWM.stop()
    GPIO.cleanup()

Explanation of PWM Code:

  • Create PWM Objects: GPIO.PWM(pin, frequency) creates a PWM object for each color. The frequency (e.g., 100 Hz) determines how often the PWM signal cycles.
  • start(0): Starts the PWM with a 0% duty cycle, meaning the LED is initially off.
  • ChangeDutyCycle(duty_cycle): Sets the duty cycle of the PWM signal. The duty cycle is a percentage (0-100) that represents the proportion of time the signal is high. A higher duty cycle means the LED is brighter.

By controlling the duty cycle of each color channel using PWM, you can create a vast range of colors.