Beginner's Guide to Controlling an RGB LED with Arduino Code


In this beginner's guide, you will look at how to control the colors of an RGB LED using Arduino code. RGB LEDs are light-emitting diodes that can produce different colors by combining red, green, and blue light. They are a fun and easy component for beginners to experiment with. This tutorial will teach you the basics of writing Arduino code to change the color of an RGB LED.

There are several packages for RBG LEDs and you could get confused with the serial controlled ones - they look the same. Here, you need to use a 'pure' RGB led with no internal chip. This way you can learn how they are really controlled at the coal face.

A serial controlled RGB LED has a microcontroller built into it which allows you to string hundreds of them together in an "RGB LED strip", and you can still control all of them them using only one pin (plus power and ground).

Here though, you will learn how to directly control an RGB LED and why you need three PWM pins to do it.

How an RGB LED Works

What is an RGB LED?

An RGB LED contains red, green, and blue LEDs embedded in a single package. By changing the intensity of each color, almost any color can be produced from the combination of red, green and blue light. They are commonly found in electronics devices like laptops, phones, and televisions to produce colored light or backlighting.

How does it change color?

By turning each individual light brighter or dimmer, you can make any color. If the red is bright and the others are off, it will look red. If green and blue are both half-bright, it will look cyan.

How do you control the brightness?

Arduino baords have pins called PWM pins that let you control the brightness of each light separately. On an Arduino Uno these are the pins that have a tilde symbol or '~' next to them beside the pin number - there are six available.

The internal PWM module pulses the voltage on and off, varying the mark to space ratio, to control the average current received by each LED. The longer each pulse is on, the brighter the light will appear. In this case the "averaging - or combination of Red, Green and Blue" , explained in that link above, is done by your eye!

You connect the red light to one PWM pin, green to another, and blue to the last one. Now you can make the red, green or blue brighter or dimmer independently with code i.e. you can create any color using different brightness of these three fundamental colors.

How do you code the colors?

In code, you set the brightness level from 0-255 for each color. 0 is off, 255 is brightest. By mixing levels, any color can be made just by adjusting the red, green and blue levels. Cool effects can be made by programming different brightness combinations over time.

Required Components

  • Arduino Uno board
  • Breadboard
  • RGB LED (common cathode)
  • 220 ohm resistors (3 per LED) - if you don't have 220 use 330 or even 1k.
  • Jumper wires

Circuit Layout

Diagram showing connections between Arduino, breadboard and RGB LED. The cathode of each Red, Green and Blue LED connects to ground while the anode pins connect to analog pins on the Arduino (~) via current-limiting resistors.

Arduino RGB LED layout diagram

Diagram using Fritzing

Schematic of an RGB LED connected to an Arduino

Arduino RGB LED schematic diagram

Diagram using Fritzing

Libraries Needed

You don't need a library as the RGB LED operation is done using three individual analog pins (~) with analogWrite.

Arduino RGB LED code Example Sketch

This the code for an RGB LED using an Arduino Uno.

// PWM pins for each color
#define RED_PIN 11
#define GREEN_PIN 10
#define BLUE_PIN 9

void setup() {
  // Set PWM pins as outputs
  pinMode(RED_PIN, OUTPUT);
  pinMode(GREEN_PIN, OUTPUT);
  pinMode(BLUE_PIN, OUTPUT);
}

void loop() {

  // Red
  analogWrite(RED_PIN, 255);
  analogWrite(GREEN_PIN, 0);
  analogWrite(BLUE_PIN, 0);
  delay(1000);

  // Green
  analogWrite(RED_PIN, 0);
  analogWrite(GREEN_PIN, 255);
  analogWrite(BLUE_PIN, 0);
  delay(1000);

  // Blue
  analogWrite(RED_PIN, 0);
  analogWrite(GREEN_PIN, 0);
  analogWrite(BLUE_PIN, 255);
  delay(1000);

  // Purple
  analogWrite(RED_PIN, 255);
  analogWrite(GREEN_PIN, 0);
  analogWrite(BLUE_PIN, 255);
  delay(1000);

  // White
  analogWrite(RED_PIN, 255);
  analogWrite(GREEN_PIN, 255);
  analogWrite(BLUE_PIN, 255);
  delay(1000);

}

Code Explanation

This code controls the color of an RGB LED using pulse-width modulation (PWM) on 3 pins of an Arduino.

Definitions

  • #define RED_PIN 9, GREEN_PIN 10, BLUE_PIN 11: Defines the pin numbers for each color channel PWM output

Setup

  • void setup():
    • Sets the PWM pins as outputs using pinMode() so they can be controlled

Loop

  • void loop():
    • Controls the LED color in a loop
    • vim Copy
    • //Red: Sets RED to max (255), others to min (0)
    • //Green: Sets GREEN to max, others to min
    • //Blue: Sets BLUE to max, others to min
    • //Purple: Combination of RED and BLUE
    • //White: Sets all channels to max
    • Uses analogWrite() to control the duty cycle (brightness) of each pin between 0-255
    • Adds a delay to view each color

The PWM pins allow analog control of LED brightness for each color channel.

Example 2 - Control from serial port

This example code allows you to enter a color specification as a hex number e.g. '#a100dd'.

Arduino is controlling the LED using PWM (pulse-width modulation) on 3 digital (PWM '~') pins - one for each color channel (Red, Green, Blue).

The analogWrite() function is used to set the duty cycle of the PWM signal, producing variable brightness levels from 0-255.

By mixing the intensity levels of the 3 primary colors, a wide range of other hues can be produced. For example, purple is red + blue.

The hex color code string follows the common #RRGGBB format, where RR, GG, and BB are 2-digit hex values for red, green an blue.

Here are some example colors to try:

#FF0000 - Red
#00FF00 - Green
#0000FF - Blue
#FFFF00 - Yellow
#FF00FF - Magenta
#00FFFF - Cyan
#FFFFFF - White
#000000 - Black
#808080 - Gray
#98FB98 - Pale Green
#FF1493 - Deep Pink
#800000 - Maroon
#00BFFF - Deep Sky Blue
#00CED1 - Dark Turquoise
#D2691E - Chocolate
#1E90FF - Dodger Blue
#B22222 - Fire Brick
#FFA500 - Orange


// Control RGB LED via serial port

#define RED_PIN 11
#define GREEN_PIN 10
#define BLUE_PIN 9

void setup() {
  pinMode(RED_PIN, OUTPUT);
  pinMode(GREEN_PIN, OUTPUT);
  pinMode(BLUE_PIN, OUTPUT);
 
  Serial.begin(9600);
}

void loop() {

  // Read color from serial if available
  if(Serial.available()) {
    String color = Serial.readString();
   
    // Extract RGB values
    int r = hexToDec(color.substring(1, 3));
    int g = hexToDec(color.substring(3, 5));
    int b = hexToDec(color.substring(5, 7));
   
    analogWrite(RED_PIN, r);
    analogWrite(GREEN_PIN, g);
    analogWrite(BLUE_PIN, b);
  }

  delay(1000);

}

int hexToDec(String hex) {
  return int(strtol(hex.c_str(), NULL, 16));
}

Code Explanation

#define Statements

    - Define constant integer values for the pins connected to each color channel (Red, Green, Blue LEDs)

void setup()

    - Configure the pinMode for each color pin as OUTPUT
    - Begin serial communication at 9600 baud

void loop()

    - Main loop that runs continuously

if(Serial.available())

    - Check if serial data is available to be read

String color = Serial.readString()

    - Read the incoming string from serial port

int r/g/b = hexToDec()

    - Extract the hex values for each color channel
    - Pass to hexToDec() function to convert from hex to decimal

analogWrite()

    - Write the converted decimal values to the PWM pins to set LED brightness

delay()

    - Add a delay to view the color

hexToDec()

    - Function to convert a hex string to decimal integer value
    - Returns the converted value

Uploading the Code

There are a few steps to uploading the code for the Arduino and PIR sensor using the Arduino IDE:

  1. Connect the Arduino Uno to the PC with a USB cable.
  2. Select the Arduino Uno hardware.
  3. Open a new sketch.
  4. Paste the code above into the new page (overwrite everything).
  5. Press the upload button (right arrow at top).

 You can find a more detailed tutorial on the Arduino IDE page.

Testing the Circuit

When you upload the code, for the RGB LED to the Arduino, it should cycle through red, green, and blue colors.

Conclusion

This tutorial has shown you how to control an RGB LED using three PWM pins. It also has two examples:

  • The first goes through basic colors in a loop,
  • The second lets you enter your own hex control values via the serial port.

This concludes the beginner's guide on controlling an RGB LED with Arduino code.

You can also create a "breathing RGB LED" here - this one looks 'cool'.



Written by John Main who has a degree in Electronic Engineering.

Note: Parts of this page were written using claude-instant as a research assistant.



Comments

Have your say about what you just read! Leave me a comment in the box below.

Don’t see the comments box? Log in to your Facebook account, give Facebook consent, then return to this page and refresh it.



Privacy Policy | Contact | About Me

Site Map | Terms of Use