LEDs
RGB LED
This sketch demonstrates how to control a 4-pin RGB LED: it cycles through a few colours, then fades the brightness of a custom colour up and down.
All three signal pins need to be PWM-capable (on an Arduino Uno: 3, 5, 6, 9, 10 or 11). See the LED hookup guide for the wiring.
The code
#include <CtrlRGBLed.h>
// A common cathode RGB LED on pins 9 (red), 10 (green) & 11 (blue), at full brightness.
CtrlRGBLed led(9, 10, 11, 255);
// A colour of your own, as red, green & blue values.
const CtrlRGB pink = {255, 51, 153};
void setup()
{
Serial.begin(9600);
led.turnOn();
}
void loop() {
// Cycle through some of the ready-made colours.
const CtrlRGB colors[] = { CtrlColor::Red, CtrlColor::Green, CtrlColor::Blue, CtrlColor::White };
for (const CtrlRGB color : colors) {
led.setColor(color);
delay(500);
}
// Fade a custom colour in and out.
led.setColor(pink);
for (int brightness = 0; brightness <= 100; brightness++) {
led.setBrightness(brightness);
delay(10);
}
for (int brightness = 100; brightness >= 0; brightness--) {
led.setBrightness(brightness);
delay(10);
}
// The colour the LED actually outputs is the colour scaled by its brightness.
const CtrlRGB output = led.getOutputColor();
Serial.print("Output: ");
Serial.print(output.r);
Serial.print(", ");
Serial.print(output.g);
Serial.print(", ");
Serial.println(output.b);
led.setBrightness(100);
}