LED strips give us a good excuse to use external libraries. We've previously looked at lighting and dimming a single LED of a single color. RGB LEDs are a bit more complex; they require PWM-ing 3 separate color channels, but we don't really need an extra library for this. However, if we want to use many RGB LEDS, the number of wires and analogWrites()
commands quickly add up to something intractable. Luckily, a number of libraries exist that make controlling these LED strips much easier. For this tutorial, we'll be using the Adafruit NeoPixel library, though we could have instead used an alternative like Pololu or FastLED. You can see all of the functions contained in the library on Adafruit's GitHub page.
First, we'll want to install the NeoPixel library with the Library Manager.
Then we'll want to wire up our RGB LED strip with a resistor between pin 9 and the DIN pad on the LED strip. Connect ground to the microcontroller's ground, and connect power to 3V.
Finally, let's look at Adafruit's page on using their library. We'll walk through the strandtest example, but first let's take a look at a minimal program to do something useful with this library:
#include <Adafruit_NeoPixel.h>
#define PIN 9
#define NUMPIXELS 10
#define DELAYVAL 500 // Time (in milliseconds) to pause between pixels
Adafruit_NeoPixel strip(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
void setup() {
strip.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
strip.show(); // Turn OFF all pixels ASAP
strip.setBrightness(10); // Set BRIGHTNESS low to reduce draw (max = 255)
}
void loop() {
strip.clear(); // Set all pixel colors to 'off'
// The first NeoPixel in a strand is #0, second is 1, all the way up
// to the count of pixels minus one.
for(int i=0; i<NUMPIXELS; i++) { // For each pixel...
// strip.Color() takes RGB values, from 0,0,0 up to 255,255,255
// Here we're using a moderately bright green color:
strip.setPixelColor(i, strip.Color(0, 150, 0));
strip.show(); // Send the updated pixel colors to the hardware.
delay(DELAYVAL); // Pause before next pass through loop
}
}
See all the available NeoPixel functions here.