RGB LEDs are a fun and easy way to add some color to your projects. Since they are like 3 regular LEDs in one, how to use and connect them is not much different.They come mostly in 2 versions: Common Anode or Common Cathode.
Common Anode uses 5V on the common pin, while Common Cathode connects to ground.
As with any LED, we need to connect some resistors inline (3 total) so we can limit the current being drawn.
In our sketch, we will start with the LED in the Red color state, then fade to Green, then fade to Blue and finally back to the Red color. By doing this we will cycle through most of the color that can be achieved.
1 x Uno R3 for Arduino
1 x Breadboard
4 x M-M wires (Male to Male jumper wires)
1 x RGB LED
3 x 330 ohm resistors
Please download sample code from RGB LED Code, paste it into Arduino IDE and upload the sketch.
The sketch starts by specifying which pins are going to be used for each of the colors:
// Define Pins
#define BLUE 3
#define GREEN 5
#define RED 6
The next step is to write the ‘setup’ function.The setup function runs just once after the Arduino has reset. In this case, all it has to do is define the three pins we are using as being outputs.
Before we take a look at the ‘loop’ function, let’s look at the last function in the sketch.
The define variables
redValue = 255; // choose a value between 1 and 255 to change the color.
greenValue = 0
blueValue = 0;
This function takes three arguments, one for the brightness of the red, green and blue LEDs. In each case the number will be in the range 0 to 255, where 0 means off and 255 means maximum brightness. The function then calls ‘analogWrite’ to set
the brightness of each LED. If you look at the ‘loop’ function you can see that we are setting the amount of red, green and blue light that we want to display and then pausing for a second before moving on to the next color.
#define delayTime 10 // fading time between colors