CNAP
03 / Templates · intermediate

RGB LED COLOUR FADE

Open in Playground

Drive all three channels of an RGB LED with PWM to mix colours and fade smoothly through the colour wheel.

intermediateRGB LEDPWMcolor mixingfade
Circuit
Code
sketch.inoArduino C++
40 lines
// RGB LED — Colour Mixing & Fade
// Fades smoothly through the colour wheel using PWM on all three channels.

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

void setColor(int r, int g, int b) {
  analogWrite(RED_PIN, r);
  analogWrite(GREEN_PIN, g);
  analogWrite(BLUE_PIN, b);
}

// Simple HSV-ish wheel: returns an RGB triple for position 0–255
void wheel(byte pos, int &r, int &g, int &b) {
  if (pos < 85) {
    r = 255 - pos * 3; g = pos * 3;       b = 0;
  } else if (pos < 170) {
    pos -= 85;
    r = 0;             g = 255 - pos * 3; b = pos * 3;
  } else {
    pos -= 170;
    r = pos * 3;       g = 0;             b = 255 - pos * 3;
  }
}

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

void loop() {
  for (int i = 0; i < 256; i++) {
    int r, g, b;
    wheel(i, r, g, b);
    setColor(r, g, b);
    delay(15);
  }
}
Components
  • Arduino Uno
    01
  • RGB LED (common cathode)
    02
  • Resistor 220Ω ×3
    03
Wiring
Component PinArduino Pin
Resistor (R leg) Pin 1Pin 9
RGB LED RedResistor (R leg) Pin 2
Resistor (G leg) Pin 1Pin 10
RGB LED GreenResistor (G leg) Pin 2
Resistor (B leg) Pin 1Pin 11
RGB LED BlueResistor (B leg) Pin 2
RGB LED Common CathodeGND