RGB LED

A RGB LED is a LED which integrates 3 LEDs of different colors (red, green, and blue) into one. As a conventional LED, it will light up by connecting the anode (+) to a voltage source (for example 3.3V) and the cathode (-) to the ground with a proper resistor. A common-anode LED has a common athode, which is the pin 1 in the schematic diagram:

As a result, connecting the pin 1 to a 3.3V power source and the pin 2, 3, or 4 to the GND (with a proper resistor), you'll see the blue, green, or red LED light up as desired. Moreover, you can connect the pin 2, 3, and/or 4 to PWM pins to make different levels of voltage go through the LED. This can give more combinations of RGB intensities and thus emits different colors. Here is an example:

  • Connect the common anode (the longest pin of the RGB LED) to a 3V3 pin

  • Connect Red, Green, and Blue pins to P17, P16, and P15, respectively, with 1KΩ resistors placed in between

Load the sketch code into the Arduino IDE:

#define R_PIN A3		// P17
#define G_PIN A2		// P16
#define B_PIN A1		// P15
#define MAX_STEP (10)

#define IS_OVER(x) (((x) >> 8) != 0)
#define CLAMP(x)   (((x) < 0)? 0: 255)

int r, g, b;
int r_dir = 1, g_dir = 1, b_dir = 1;

void setup()
{
    // initialize the pin directions
    pinMode(R_PIN, OUTPUT);
    pinMode(G_PIN, OUTPUT);
    pinMode(B_PIN, OUTPUT);
}
void loop()
{
    // walk in a random step
    r += random(MAX_STEP) * r_dir;
    g += random(MAX_STEP) * g_dir;
    b += random(MAX_STEP) * b_dir;

    // check if it walks out of the boundary and thus needs to turn back
    if (IS_OVER(r)) { r = CLAMP(r); r_dir = -r_dir; }
    if (IS_OVER(g)) { g = CLAMP(g); g_dir = -g_dir; }
    if (IS_OVER(b)) { b = CLAMP(b); b_dir = -b_dir; }

    // Set the output value
    analogWrite(R_PIN, r);
    analogWrite(G_PIN, g);
    analogWrite(B_PIN, b);

    delay(50);
}

After clicking the Upload button to upload the codes to the board, you'll see the LED keeps changing its color over time.

Note

A LED will be on only when the cathode is below the voltage of the anode.

Therefore, in the above example where the anode is with 3.3V, if one analog pin, connected to one of the cathodes of the LED, outputs at its highest voltage level (3.3V), the LED will be off in the selected channel. On the other hand, if the analog pin outputs at its lowest voltage level (0V), it makes the LED be in the brightest state of that channel.

Last updated