Introduction
In this experiment, you will learn how to control an RGB LED using an Arduino. By adjusting the brightness of the red, green, and blue channels, you can create a variety of colors.
Components Needed
Circuit Setup
- Place the RGB LED on the breadboard. The longest leg is the common cathode (ground).
- Connect the common cathode leg of the RGB LED to the ground (GND) on the Arduino.
- Connect the red, green, and blue legs of the LED to pins 9, 10, and 11 on the Arduino, each through a 270-ohm resistor.
Note: Each resistor limits the current for its respective color channel to prevent damage to the LED.
Code for RGB LED Control
Upload the following code to your Arduino to control the colors of the RGB LED by adjusting the brightness of each color channel:
// Define the pins for each color
const int redPin = 9;
const int greenPin = 10;
const int bluePin = 11;
void setup() {
// Set each RGB LED pin as output
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop() {
// Cycle through colors by adjusting RGB values
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);
}
void setColor(int red, int green, int blue) {
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}
Explanation
This code uses the analogWrite()
function to adjust the brightness of each color channel. The setColor()
function takes three parameters (red, green, blue) and sets the brightness of each channel from 0 to 255.
By mixing different values, you can create various colors. The delay()
between each color change creates a visible transition effect.
Troubleshooting
- If the colors are not displaying correctly, check the connections for each LED pin.
- Ensure that the resistors are connected in series with each color channel to prevent excessive current.
- Try adjusting the delay time to see faster or slower transitions between colors.