RGB LED

1 minute read

RGB LEDs typically have 4 pins: Red, Green, Blue, and Common Cathode (or Common Anode).

For a Common Cathode RGB LED, each color pin is connected to a PWM-capable pin on the Arduino.

If you’re using a Common Anode RGB LED, you’ll need to reverse the logic (use HIGH to turn the color on and LOW to turn it off).

Make sure to use current-limiting resistors (typically 220Ω to 330Ω) for each color pin to avoid burning out the LED.

Color combinations from RGB

  • Yellow (Red + Green)
  • Cyan (Green + Blue)
  • Magenta (Red + Blue)
  • White (Red + Green + Blue)
const int colors[7][3] = {
  {HIGH, LOW, LOW},    // Red
  {LOW, HIGH, LOW},    // Green
  {LOW, LOW, HIGH},    // Blue
  {HIGH, HIGH, LOW},   // Yellow (Red + Green)
  {LOW, HIGH, HIGH},   // Cyan (Green + Blue)
  {HIGH, LOW, HIGH},   // Magenta (Red + Blue)
  {HIGH, HIGH, HIGH},  // White (Red + Green + Blue)
};

Full code

// Pin definitions for RGB LED
const int redPin = 9;    // Red pin connected to Pin 9
const int greenPin = 10;  // Green pin connected to Pin 10
const int bluePin = 11;   // Blue pin connected to Pin 11

void setup() {
  // Set RGB pins as OUTPUT
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  
  // Initially turn off the RGB LED (set all pins to LOW)
  setColor(LOW, LOW, LOW);
}

void loop() {
  // Cycle through all possible combinations of (0, 0, 0) to (1, 1, 1)
  for (int r = 0; r <= 1; r++) {        // Loop for Red: 0 or 1
    for (int g = 0; g <= 1; g++) {      // Loop for Green: 0 or 1
      for (int b = 0; b <= 1; b++) {    // Loop for Blue: 0 or 1
        setColor(r, g, b);              // Set the RGB color
        delay(500);                     // Wait for 0.5 second before changing color
      }
    }
  }

  // Turn off the RGB LED after cycling through colors
  setColor(LOW, LOW, LOW);
  delay(1000); // Wait for 1 second before looping again
}

// Function to set the color by writing to the pins
void setColor(int red, int green, int blue) {
  digitalWrite(redPin, red);
  digitalWrite(greenPin, green);
  digitalWrite(bluePin, blue);
}