Control an RGB LED with Arduino Uno

Control an RGB LED with Arduino Uno

Welcome back to Maker Tech Lab! In this tutorial, we will show you how to control an RGB LED with an Arduino Uno. You will learn how to mix different colors using pulse-width modulation (PWM).

Materials Needed

  • Arduino Uno
  • RGB LED
  • 220-ohm resistors (3)
  • Breadboard
  • Jumper wires

Circuit Diagram

Let’s set up the circuit. Follow the diagram below:

  1. Connect the RGB LED: Place the RGB LED on the breadboard. The longest pin is the common ground (cathode). Connect this pin to the ground (GND) on the Arduino.
  2. Connect the Resistors: Connect a 220-ohm resistor to each of the other three pins (red, green, and blue) of the RGB LED.
  3. Connect the Resistors to Arduino: Connect the other end of the resistors to digital pins on the Arduino (e.g., pins 9, 10, and 11).

The Code

Let’s move on to the code. We’ll use the Arduino IDE to write a program that controls the RGB LED using PWM.


const int redPin = 9;// Pins for the RGB LED
const int greenPin = 10;
const int bluePin = 11;

// Setup function runs once when you press reset or power the board
void setup() {
// Initialize the RGB LED pins as outputs
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}

// Loop function runs over and over again forever
void loop() {
// Call the function to set the RGB color
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 the RGB color
void setColor(int red, int green, int blue) {
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}

Explanation

  • Pin Setup: We define the pins where the RGB LED is connected.
  • Setup Function: We initialize the RGB LED pins as outputs.
  • Loop Function: This function runs repeatedly. It sets different colors for the RGB LED with a delay of 1 second for each color.
  • SetColor Function: This function sets the color of the RGB LED by writing PWM values to the red, green, and blue pins.

Uploading the Code

  1. Open the Arduino IDE.
  2. Copy and paste the code into the IDE.
  3. Select the correct board and port from the Tools menu.
  4. Click the upload button.

Conclusion

That’s it! You’ve successfully created a project that controls an RGB LED using an Arduino Uno. This project introduces the concept of PWM and color mixing, which can be applied to a variety of projects. Stay tuned for more tutorials and exciting projects at Maker Tech Lab!

Leave a Comment

Buy samsung galaxy watch 6.