Try Embedded

RGB LED colour fade

Mix red, green and blue with PWM to fade an RGB LED smoothly around the colour wheel.

Output · Beginner

In a real product: Mood lamp (Smart home): PWM mixes any colour.

An RGB LED is three LEDs (red, green and blue) in one package. Setting each one's brightness with PWM mixes them into any colour. This project fades smoothly from red to green to blue and back.

What you'll learn

  • What PWM is, and how analogWrite() uses it to set brightness
  • Which Uno pins can do PWM (the ones marked ~: 3, 5, 6, 9, 10, 11)
  • Common-cathode versus common-anode RGB LEDs

How it works

This LED is common cathode: its three cathodes share the COM pin, which goes to GND. Each colour's anode goes to a PWM pin through its own 220 Ω resistor: red to 11, green to 10 and blue to 9.

analogWrite(pin, value) switches the pin on and off about 490 times a second. value (0 to 255) sets how much of each cycle it is on. At 128 the LED is on half the time and looks half as bright, because your eye averages the flicker.

The loop has three fades. In each, one colour ramps down while the next ramps up, so the total brightness stays the same and the colour moves around the wheel.

Each colour needs its own resistor. One shared resistor on COM would let the colours steal current from each other, so the mix would shift as their brightness changes.

Try this

  • Make it common anode (set the part's common to anode, wire COM to 5V) and invert the values: 255 - value.
  • Add a potentiometer and use it to pick the hue.
  • Show a traffic light sequence: red, red and green (yellow), green.

sketch.ino

// Fade an RGB LED (common cathode) through the colour wheel with PWM on pins 11, 10 and 9.
const int RED = 11, GREEN = 10, BLUE = 9;

void setColor(int r, int g, int b) {
  analogWrite(RED, r);
  analogWrite(GREEN, g);
  analogWrite(BLUE, b);
}

void setup() {
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
}

void loop() {
  for (int i = 0; i < 256; i++) { setColor(255 - i, i, 0); delay(8); }  // red to green
  for (int i = 0; i < 256; i++) { setColor(0, 255 - i, i); delay(8); }  // green to blue
  for (int i = 0; i < 256; i++) { setColor(i, 0, 255 - i); delay(8); }  // blue to red
}

Lessons behind it