Mix colours with the RGB LED module

Drive the red, green and blue parts of the RGB LED module with PWM and mix any colour you like.
  • Level:Beginner
  • Duration: 35 min
  • Ages 10+
  • Platform: Arduino

What you'll need

Mix colours with the RGB LED module – EEMENTOR STEM lesson

An RGB LED is really three LEDs in one package: red, green and blue. By changing how bright each one is, you can mix almost any colour, just like the pixels on a screen.

What you'll learn

  • What PWM (pulse-width modulation) is
  • How to use analogWrite()
  • How colours are mixed from red, green and blue

What you need

  • UNO R3 board (or any Arduino-compatible board) and USB cable
  • RGB LED module from the 45-in-1 kit
  • Breadboard
  • 3 resistors, 220 Ω
  • Jumper wires

Wiring

Check the labels on your module: R, G, B and − (the common ground). A 220 Ω resistor in each colour line protects the LED, even if your module already has resistors on board.

Breadboard wiring diagram: Mix colours with the RGB LED module
Breadboard view. Check each connection against the wiring table below.
From Through To
UNO pin 9 220 Ω resistor Module R
UNO pin 10 220 Ω resistor Module G
UNO pin 11 220 Ω resistor Module B
Module − UNO GND

The sketch

const int RED_PIN = 9;
const int GREEN_PIN = 10;
const int BLUE_PIN = 11;

void setColor(int red, int green, int blue) {
  analogWrite(RED_PIN, red);     // 0 = off, 255 = full brightness
  analogWrite(GREEN_PIN, green);
  analogWrite(BLUE_PIN, blue);
}

void setup() {
  pinMode(RED_PIN, OUTPUT);
  pinMode(GREEN_PIN, OUTPUT);
  pinMode(BLUE_PIN, OUTPUT);
}

void loop() {
  setColor(255, 0, 0);    // red
  delay(1000);
  setColor(0, 255, 0);    // green
  delay(1000);
  setColor(0, 0, 255);    // blue
  delay(1000);
  setColor(255, 255, 0);  // yellow
  delay(1000);
  setColor(0, 255, 255);  // cyan
  delay(1000);
  setColor(255, 0, 255);  // magenta
  delay(1000);
  setColor(255, 255, 255); // white
  delay(1000);
}

How it works

Pins 9, 10 and 11 support PWM, marked with a ~ on the board. PWM switches the pin on and off very fast, hundreds of times per second. analogWrite(pin, 128) keeps it on about half the time, which your eye sees as half brightness. Mixing red and green gives yellow, green and blue gives cyan, and all three together give white.

Try this next

  • Make a smooth rainbow by slowly changing the values in a for loop.
  • Combine this with the night light lesson: the darker the room, the bluer the light.

Troubleshooting

  • A colour is missing: check that colour's resistor and wire, and that it goes to pin 9, 10 or 11.
  • The colours are inverted (white when it should be off): you have a common-anode LED. Connect its common pin to 5V instead of GND, and use 255 - value in setColor().

Build it yourself

Everything used in this lesson comes in one kit, with parts tested by our engineers.

45-in-1 Sensor Kit | Compatible with Arduino IDE and ESP32 $29.00

Shop the kit