int redPin= 11;
int greenPin = 10;
int bluePin = 9 ;
void setup() {
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop() {
setColor(255, 0, 0); // Red Color
delay(1000);
setColor(0, 255, 0); // Green Color
delay(1000);
setColor(0, 0, 255); // Blue Color
delay(1000);
setColor(255, 255, 255); // White Color
delay(1000);
setColor(170, 0, 255); // Purple Color
delay(1000);
setColor(255,255,0);
delay(1000);
setColor(128,0,128);
delay(1000);
setColor(64,224,208);
delay(1000);
setColor(0,128,128);
delay(1000);
setColor(128,0,0);
delay(1000);
setColor(0,0,128);
delay(1000);
}
void setColor(int redValue, int greenValue, int blueValue) {
analogWrite(redPin, redValue);
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
}
Understanding RGB Color Mixing
An RGB LED is essentially three LEDs (Red, Green, and Blue) packed into a single module with shared connections (either a Common Cathode or Common Anode). By adjusting the brightness of each internal LED independently, we can create almost any color in the visible spectrum through Additive Color Mixing.
Hardware Setup
- Arduino Pins: We use Pins 9, 10, and 11 because they are hardware-enabled PWM (Pulse Width Modulation) pins. This allows the Arduino to simulate varying voltages by rapidly switching the output ON and OFF.
- Connection:
- Red Pin -> Digital Pin 11
- Green Pin -> Digital Pin 10
- Blue Pin -> Digital Pin 9
- Common Pin -> Ground (for Common Cathode) or 5V (for Common Anode)
Code Explanation: The setColor Function
The core of this project is a custom function setColor(int r, int g, int b). It simplifies the code by allowing us to pass values from 0 (off) to 255 (full brightness) for each color channel.
void setColor(int redValue, int greenValue, int blueValue) {
analogWrite(redPin, redValue);
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
}
Using analogWrite(), the Arduino generates a square wave with a duty cycle corresponding to the input value, which our eyes perceive as dimmed or bright color levels.
Experimenting with Colors
By combining different values, you can create specialty colors:
- Purple:
setColor(170, 0, 255) - Turquoise:
setColor(64, 224, 208) - Yellow:
setColor(255, 255, 0)
This project's logical structure makes it easy to add more complex patterns, such as smooth color transitions (rainbow fades) or environmental color sensing in future iterations.