In this article we simply show you 4 examples using an RGB LED connected to an Arduino
The RGB led we had was a common anode type, so if you only have common cathode one’s available you will have to modify the code examples later on
RGB LEDs are tri-color LEDs with red, green, and blue emitters, in general using a four-wire connection with one common lead (anode or cathode).
Connection
We used an all in one module but its connected something like this
Red Pin -> Arduino Pin 9
Green Pin ->Arduino Pin 10
Blue Pin -> Arduino Pin 11
Common Anode -> Arduino 5v
This shows what we mean, this is based on building the circuit with individual components. There are several RGB LED modules which make connection easy – no breadboards.
Parts List
Description | Link |
Arduino Uno | 1pcs UNO R3 CH340G+MEGA328P for Arduino UNO R3 (NO USB CABLE) |
RGB LED breakout | 1pcs RGB LED Breakout Module RGB LED Module RGB module |
connecting wire | 40pcs Dupont jumper wire cable 30cm male to male,female to female,male to female Dupont jump wire line 2.54mm breadboard cable |
Code Examples
We have 4 fairly simple code examples that will flash various colours
Example 1
[codesyntax lang=”cpp”]
//cycle through red, green and blue
void setup()
{
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
//common anode type
digitalWrite(9, HIGH);
digitalWrite(10, HIGH);
digitalWrite(11, HIGH);
}
void loop()
{
digitalWrite(9, LOW); // red on
delay(1000);
digitalWrite(9, HIGH); //red off
digitalWrite(10, LOW); //green on
delay(1000);
digitalWrite(10, HIGH); //green off
digitalWrite(11, LOW); //blue on
delay(1000);
digitalWrite(11, HIGH); //blue off
}
[/codesyntax]
Example 2
[codesyntax lang=”cpp”]
//random red, green and blue
long randNumber;
void setup()
{
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
//common anode type
digitalWrite(9, HIGH);
digitalWrite(10, HIGH);
digitalWrite(11, HIGH);
Serial.begin(9600);
randomSeed(analogRead(0));
}
void loop()
{
randNumber = random(9, 12); //random 9,10 or 11
digitalWrite(randNumber, LOW);
//Serial.println(randNumber);
delay(100);
digitalWrite(randNumber, HIGH);
}
[/codesyntax]
Example 3
[codesyntax lang=”cpp”]
//fading red, green and blue
void setup()
{
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
}
void loop()
{
for(int r = 0; r < 255; r++)
{
analogWrite(9, r);
delay(10);
}
for(int g = 0; g < 255; g++)
{
analogWrite(10, g);
delay(10);
}
for(int b = 0; b < 255; b++)
{
analogWrite(11, b);
delay(10);
}
}
[/codesyntax]
Example 4
[codesyntax lang=”cpp”]
long redNumber;
long greenNumber;
long blueNumber;
void setup()
{
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
Serial.begin(9600);
randomSeed(analogRead(0));
}
void loop()
{
redNumber = random(256);
greenNumber = random(256);
blueNumber = random(256);
analogWrite(9, redNumber);
analogWrite(10, greenNumber);
analogWrite(11, blueNumber);
delay(100);
}
[/codesyntax]
Video
A video showing the examples above