RGB LEDs have three individual LEDs inside—red, green, and blue. These LEDs usually share a common connection, which can either be a cathode (negative terminal) or an anode (positive terminal). This means RGB LEDs are categorized as either common anode (shared positive terminal) or common cathode (shared negative terminal).
In this project, we are using a common cathode (shared negative terminal) RGB LED. For a common cathode LED, all three LEDs share a single cathode connection (negative), and the individual anodes (positive terminals) control the red, green, and blue LEDs separately.
Anode and Cathode
- Anode: The positive terminal of an LED, where current flows into the LED.
- Cathode: The negative terminal of an LED, where current flows out of the LED.


You might think a single resistor on the common pin is sufficient, but it’s best to use three separate resistors, one for each color. This ensures safe operation, consistent brightness, and accurate color mixing. Without individual resistors, the LEDs’ brightness won’t be properly balanced, leading to inaccurate color blending.
The following code first displays red, green, and blue to verify that the RGB LED is working properly. In the loop, the RGB LED shows a random color every second.
The variables redLed, greenLed, and blueLed are assigned to the digital pins 22, 21, and 19, respectively. These pins will control the Red, Green, and Blue LEDs of the RGB LED.
The setRGBLed function is used to control the state of the RGB LED. It takes three parameters: isRedOn, isGreenOn, and isBlueOn, which are bool values representing whether the respective LEDs should be on (true) or off (false).
This function controls the corresponding LED based on the values passed (true or false), instead of using HIGH and LOW. In this case, true and HIGH both represent 1, while false and LOW both represent 0.
In the setup() function, the pinMode function is used to set the pins for the RGB LEDs (redLed, greenLed, and blueLed) as OUTPUT so that they can send signals to control the LEDs.
This is initial LED Test. The setRGBLed function is called four times in a sequence to turn Red, Green ,Blue on and then off. Each of these calls has a 1-second delay between them due to the delay(1000) in the setRGBLed function.
The random() function generates random numbers.
min: The smallest value in the range (inclusive).
max: The largest value in the range (exclusive).
In this case, random(0, 10) generates a random integer between 0 and 9 (inclusive of 0 but exclusive of 10).
The loop() function runs repeatedly, generating a random combination of red, green, and blue light. The random(0, 2) function generates either 0 or 1, representing off (0) or on (1). isRedOn, isGreenOn, and isBlueOn are assigned random values (either 0 or 1). Since loop() runs repeatedly, the RGB LED will change to a new random color every second, as the random values change on each iteration.