Difficulty Level: Beginner
This tutorial will show how to control the color and brightness of an RGB LED using an Arduino. Each color (Red, Green, and Blue) can be independently controlled to create various color combinations.
Connect the RGB LED to the Arduino as follows:
RGB LEDs consist of three LEDs (Red, Green, Blue) combined into one package. By adjusting the brightness of each individual LED using PWM, you can create different colors. The Arduino will control the brightness of each color channel using the analogWrite()
function, which outputs PWM signals.
In this code, we use three PWM pins (pins 9, 10, and 11) to control the red, green, and blue components of the RGB LED. By adjusting the PWM values, we can mix different amounts of red, green, and blue to create various colors.
Here is the Arduino code to control an RGB LED:
int redPin = 9; // Red LED pin
int greenPin = 10; // Green LED pin
int bluePin = 11; // Blue LED pin
void setup() {
// Set the RGB pins as output
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop() {
// Cycle through different colors
setColor(255, 0, 0); // Red
delay(1000);
setColor(0, 255, 0); // Green
delay(1000);
setColor(0, 0, 255); // Blue
delay(1000);
setColor(255, 255, 0); // Yellow
delay(1000);
setColor(0, 255, 255); // Cyan
delay(1000);
setColor(255, 0, 255); // Magenta
delay(1000);
setColor(255, 255, 255); // White
delay(1000);
}
// Function to set RGB color
void setColor(int redValue, int greenValue, int blueValue) {
analogWrite(redPin, redValue);
analogWrite(greenPin, greenValue);
analogWrite(bluePin, blueValue);
}
setColor()
function to create your own custom colors.If you'd like to control the brightness of each color manually, you can add three potentiometers to the circuit and adjust the PWM values based on the potentiometer readings.
// Use 3 potentiometers to control the RGB values
int potRed = A0;
int potGreen = A1;
int potBlue = A2;
void loop() {
int redValue = analogRead(potRed) / 4;
int greenValue = analogRead(potGreen) / 4;
int blueValue = analogRead(potBlue) / 4;
setColor(redValue, greenValue, blueValue);
delay(10);
}
By controlling the individual colors of an RGB LED, you can create a wide range of colors and even dynamic lighting effects. This project is an excellent way to understand how PWM and color mixing work.