Fade an LED and mix colours with an RGB LED on the Raspberry Pi

Make an LED glow at any brightness, then mix red, green and blue light into any colour you like. You learn PWM, the trick the Raspberry Pi uses to dim an LED, and program it in Python with gpiozero.
  • Level:Beginner
  • Duration: 40 min
  • Ages 10+
  • Platform: Raspberry Pi

What you'll need

Fade an LED and mix colours with an RGB LED on the Raspberry Pi – EEMENTOR STEM™ lesson

A normal GPIO pin can only be on or off, yet the Raspberry Pi can make an LED glow softly, fade in and out, or shine in any colour of the rainbow. The trick is called PWM: the pin switches on and off so fast that your eyes only see the average. In this lesson you first fade one colour up and down, then mix red, green and blue light in an RGB LED to make yellow, cyan, purple, orange and white. You program it all in Python with gpiozero's RGBLED.

What you'll learn

  • How PWM makes an LED look brighter or dimmer
  • How an RGB LED mixes red, green and blue into other colours
  • How to set a colour in Python with three numbers from 0 to 1
  • How to make an LED "breathe" with pulse()

What you need

  • Raspberry Pi 4 Model B with Raspberry Pi OS on a microSD card (see the first lesson) and its USB-C power supply
  • RGB LED and 3 × 220 Ω resistors (ESP32 IoT Starter Kit)
  • Breadboard (ESP32 IoT Starter Kit)
  • Female-to-male jumper wires, to go from the Pi's pins to the breadboard. If you don't have any, plug a female-female and a male-male Dupont wire from the ESP32 IoT Starter Kit together.

Look after your Pi: the GPIO pins work at 3.3 V. Never connect 5 V (or the 5V pins) to a GPIO pin, never connect a GPIO pin straight to GND or to 3.3 V with a plain wire, never connect a 3V3 or 5V pin to GND, and always shut the Pi down and unplug it before you change the wiring. A single wrong wire can damage the Pi for good.

Wiring

The RGB LED has four legs. The longest one is the shared minus leg (the "common cathode"). Hold the LED so the longest leg is second from the left: the legs are then red, minus, green, blue. Each colour gets its own 220 Ω resistor, and the minus leg goes to GND.

Breadboard wiring diagram: RGB LED with three 220 ohm resistors, red to GPIO 17 (pin 11), green to GPIO 27 (pin 13), blue to GPIO 22 (pin 15), the longest leg to GND (pin 9) on a Raspberry Pi 4.
Breadboard view. Check each connection against the wiring table below.
From To
GPIO 17 (pin 11) 220 Ω resistor → RGB LED red leg
GPIO 27 (pin 13) 220 Ω resistor → RGB LED green leg
GPIO 22 (pin 15) 220 Ω resistor → RGB LED blue leg
RGB LED longest leg (−) The blue (−) rail
The blue (−) rail GND (pin 9)

The program

Open Thonny (Raspberry menu → Programming → Thonny), paste the program into a new file, save it in your home folder as rgb_mixer.py, and click the green Run button. Press the red Stop button (or Ctrl+C) to stop it. gpiozero is already installed on Raspberry Pi OS.

# Fade an LED and mix colours with an RGB LED (gpiozero, PWM)
from gpiozero import RGBLED
from time import sleep
from signal import pause

led = RGBLED(red=17, green=27, blue=22)   # common cathode: longest leg to GND

colours = {
    "red":     (1, 0, 0),
    "green":   (0, 1, 0),
    "blue":    (0, 0, 1),
    "yellow":  (1, 1, 0),
    "cyan":    (0, 1, 1),
    "magenta": (1, 0, 1),
    "orange":  (1, 0.25, 0),
    "white":   (1, 1, 1),
}

print("Part 1: fade red up and down")
for step in list(range(0, 101, 5)) + list(range(100, -1, -5)):
    led.color = (step / 100, 0, 0)        # 0 = off, 1 = full brightness
    sleep(0.05)

print("Part 2: mix colours")
for name, rgb in colours.items():
    print(f"{name:8} red={rgb[0]}  green={rgb[1]}  blue={rgb[2]}")
    led.color = rgb
    sleep(1.5)

print("Part 3: breathe in purple. Press Stop to end.")
led.pulse(fade_in_time=1.5, fade_out_time=1.5, on_color=(0.6, 0, 1))
pause()                                   # keep the program running

Try it

  1. Run the program. The LED glows red, slowly gets brighter, then fades out again.
  2. The colours follow one by one, and the Shell prints the three numbers for each one. Look at how yellow is just red and green together.
  3. At the end the LED breathes in purple until you press Stop.
  4. Change the numbers: try (1, 0.5, 0), (0.2, 0, 1) or (1, 0.6, 0.3) and give your colour a name in the list.

What you should see

Thonny Shell output of rgb_mixer.py: the fade, then each colour name with its red, green and blue values, then the purple breathing part.
The Shell prints each colour while the LED shows it.

How it works

PWM at 25, 50 and 100 percent with the LED getting brighter, and how red, green and blue light mix into yellow, cyan, magenta, white and orange.
PWM sets the brightness of each colour; your eyes mix the three.

The Pi can't put "half" a voltage on a pin. Instead, RGBLED uses PWM (pulse-width modulation): it switches each pin on and off many times a second. If the pin is on for a quarter of the time, the LED gets a quarter of the light and looks dim; on all the time, it is at full brightness. The share of time it is on is called the duty cycle, and in gpiozero it is the number from 0 to 1 that you give it.

An RGB LED is really three tiny LEDs in one case: red, green and blue. Your eyes mix their light, so red and green together look yellow, green and blue look cyan, and all three look white. With three numbers between 0 and 1 you can make thousands of colours, the same way the pixels on a phone screen do.

led.color = (1, 0.25, 0) sets all three at once: full red, a quarter green, no blue, which gives orange. pulse() fades the LED in and out by itself in the background, so the program only needs pause() to keep running.

Try this next

  • Make a colour picker: ask for three numbers with input() and show the colour you typed.
  • Add the push button from the button lesson and make each press show the next colour.
  • Make a mood lamp that drifts slowly through all the colours, changing a little every tenth of a second.
  • Next lesson: measure distance with an ultrasonic sensor.

Troubleshooting

  • The colours are wrong (red shows as green): two colour wires are swapped. Check which leg goes to GPIO 17, 27 and 22, using the leg order red, minus, green, blue.
  • The LED is on when it should be off, and the colours look inverted: your LED is a common anode type. Move the longest leg from GND to 3V3 (pin 1) and write RGBLED(red=17, green=27, blue=22, active_high=False).
  • One colour never lights: check that colour's resistor and wire, and that the resistor really connects to the right leg.
  • "GPIO busy" or "pin already in use": an earlier run is still going. Press Stop in Thonny and run it again.
  • Always shut down properly: click the Raspberry menu → Shutdown, or type sudo shutdown now, and wait until the green light stops flashing before you unplug the power. Pulling the plug while the Pi is working can damage the files on the microSD card.