From charlesreid1

In which we create circuits to control an RGB LED...

Overview

The RGB LED has three different colors of LED inside of it. Like a pixel on a computer screen, you can control the output of all three lights to create different colors. For example, to make purple, you'd turn on the red and blue LEDs and turn off the green LED.

Hello World

This is a simple circuit to turn on the LED and cycle through different colors.

The Circuit

Breadboard Diagram

The following is a diagram of the breadboard layout for our simple Hello World program.

Bb RGB LED.png

With our Hello World Arduino Micro project we already encountered resistors ahead of an LED. We do the same thing here, except now, instead of a single wire connecting to a single resistor ahead of a single LED, we have three wires connecting to three resistors ahead of three legs of our single RGB LED.

Diagram RGB LED.png

The longest leg is always the negative.

Breadboard Photograph

Here is a photograph of the final breadboard arrangement with the Arduino Leo:

Photo RGB LED bb.jpg

and a photo of the LED itself:

Photo RGB LED.jpg

Sketch Code

The following sketch code changes the color of the LED, running through a series of colors.

/*
Adafruit Arduino - Lesson 3. RGB LED

from https://learn.adafruit.com/adafruit-arduino-lesson-3-rgb-leds/arduino-sketch
*/
 
int redPin = 11;
int greenPin = 10;
int bluePin = 9;
 
//uncomment this line if using a Common Anode LED
//#define COMMON_ANODE
 
void setup()
{
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);  
}
 
void loop()
{
  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(80, 0, 80);  // purple
  delay(1000);
  setColor(0, 255, 255);  // aqua
  delay(1000);
}
 
void setColor(int red, int green, int blue)
{
  #ifdef COMMON_ANODE
    red = 255 - red;
    green = 255 - green;
    blue = 255 - blue;
  #endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);  
}

References