Skip to content

CPP: NeoPixels

Leo Vidarte edited this page Mar 7, 2017 · 8 revisions

NeoPixels, also known as WS2812 LEDs, are full-colour LEDs that are connected in serial, are individually addressable, and can have their red, green and blue components set between 0 and 255. They require precise timing to control them and there is a special neopixel module to do just this.

PlatformIO lib installation

We need the Neopixel Adafruit library, but it is easy with PlatformIO from command line:

$ platformio lib install https://github.com/adafruit/Adafruit_NeoPixel.git
Library Storage: /home/lvidarte/Projects/esp8266/NeoPixels/.piolibdeps
LibraryManager: Installing Adafruit_NeoPixel
git version 2.7.4
Cloning into '/home/lvidarte/Projects/esp8266/NeoPixels/.piolibdeps/installing-tuhmeX-package'...
remote: Counting objects: 23, done.
remote: Compressing objects: 100% (22/22), done.
remote: Total 23 (delta 1), reused 11 (delta 0), pack-reused 0
Unpacking objects: 100% (23/23), done.
Checking connectivity... done.

Code

#include <Adafruit_NeoPixel.h>

#define NUM_PIXELS 10
#define PIN_PIXELS 14

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUM_PIXELS, PIN_PIXELS, NEO_GRB + NEO_KHZ800);

void setup ()
{
  pixels.begin();
}

void loop ()
{
  int i;
  for (i = 0; i < NUM_PIXELS; i++)
  {
    pixels.setPixelColor(i, pixels.Color(127, 0, 0));
    pixels.show();
    delay(500);
  }

  for (i = NUM_PIXELS - 1; i >= 0; i--)
  {
    pixels.setPixelColor(i, pixels.Color(0, 127, 0));
    pixels.show();
    delay(500);
  }
}

Checkout this PlatformIO Project code at https://github.com/lvidarte/esp8266/tree/master/examples/neopixels/src/c%2B%2B/neopixels