Software

The rpi_ws281x library is the key that makes using NeoPixels with the Raspberry Pi possible.

Compile & Install rpi_ws281x Library

These steps will show you how to compile the rpi_ws281x library and install a Python wrapper around it.

To start, connect to a terminal on the Raspberry Pi and execute the following commands to install some dependencies:

sudo apt-get update
sudo apt-get install build-essential python-dev git scons swig

Now run these commands to download the library source and compile it:

git clone https://github.com/jgarff/rpi_ws281x.git
cd rpi_ws281x
scons

After running the scons command above you should see the library successfully compiled.  Next you can install the Python library by executing:

cd python
sudo python setup.py install

After running those commands the Python wrapper around the rpi_ws281x library should be generated and installed.

Inside the examples subdirectory you can find a couple examples of using the library.  strandtest.py is an example of using the high-level Python library which looks like the Arduino NeoPixel library.  lowlevel.py is an example of using the lower level SWIG-generated wrapper around the rpi_ws281x library.  You probably don't want to use the low level API unless you're writing your own library--stick to using the higher level API in strandtest.py!

Strandtest Example

To demonstrate the usage of the NeoPixel Python wrapper I'll walk through the code for the strandtest.py example.  First to run example make sure your hardware is setup as described on the previous page.  Then open standtest.py in a text editor and scroll down to the section of code that configures the LEDs here:

# LED strip configuration:
LED_COUNT   = 16      # Number of LED pixels.
LED_PIN     = 18      # GPIO pin connected to the pixels (must support PWM!).
LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
LED_DMA     = 5       # DMA channel to use for generating signal (try 5)
LED_INVERT  = False   # True to invert the signal (when using NPN transistor level shift)

Change the value of LED_COUNT to be the number of LEDs in your NeoPixel strand/board/ring.  The rest of the settings don't need to be changed, but they're good to review in case you change the hardware in the future.  

Save the file, and then run it by executing:

sudo python strandtest.py

Make sure to run the script as root by using the sudo command.  The rpi_ws281x library has to access the Pi hardware at a low level and requires running as root!

It might take a few seconds for the program to initialize and then you should see the NeoPixels light up and animate in different color wipes, theater lights, and rainbow animations.  Press Ctrl-C at any time to quit the example.  If you see an error about glibc detected double free or corruption you can ignore it (when the program is exited with Ctrl-C it can sometimes abruptly kill the process before it can gracefully clean-up its memory).

To understand how to use the high level Python wrapper open strandtest.py in a text editor again and follow along below.

import time

from neopixel import *

At the top of the script are the module imports.  In this example the Python standard time module is included to access its sleep function.  More importantly though the next line imports all the functions from the neopixel module.  This neopixel module defines the high-level wrapper around the rpi_ws281x library.

# LED strip configuration:
LED_COUNT   = 16      # Number of LED pixels.
LED_PIN     = 18      # GPIO pin connected to the pixels (must support PWM!).
LED_FREQ_HZ = 800000  # LED signal frequency in hertz (usually 800khz)
LED_DMA     = 5       # DMA channel to use for generating signal (try 5)
LED_INVERT  = False   # True to invert the signal (when using NPN transistor level shift)

The next lines are what you saw earlier to configure the LEDs.  In particular make sure the count and pin are set to what you're using with your hardware.  Be careful with the pin value because it must be a pin that supports hardware PWM on the Pi, like pin 18.

The remaining configuration generally doesn't need to change, but for reference you can control the frequency of the NeoPixel control signal (typically 800khz, but sometimes 400khz), DMA channel (try 5, but there are 15 channels with values 0-14 available), and a boolean to invert the control signal.  You might need to invert the control signal if you're using a NPN transistor as a level-converter (not described in this guide).

# Define functions which animate LEDs in various ways.
def colorWipe(strip, color, wait_ms=50):
	"""Wipe color across display a pixel at a time."""
	for i in range(strip.numPixels()):
		strip.setPixelColor(i, color)
		strip.show()
		time.sleep(wait_ms/1000.0)

Next a few functions are defined to run the animations in the example.  These functions take in an Adafruit_NeoPixel object (defined later in the code) as their first parameter and call functions on that object to set LED colors.  In particular you can see these functions are used on the Adafruit_NeoPixel object:

  • numPixels() - This function returns the number of pixels in the LED strip/matrix/ring/etc.  This is handy when looping through all the pixels to animate or change them in some way.
  • setPixelColor(pos, color) - This function sets the LED pixel at position pos to the provided color.  Color should be a 24-bit value where the upper 8 bits are the red value, middle 8 bits are the green value, and lower 8 bits are the blue value.  You'll actually see a little later in the sketch a helper function that lets you define a color with just these red, green, blue component values.
  • setPixelColorRGB(pos, red, green, blue) - Although not shown in this example, you can call this function to set the color of a pixel directly using the specified red, green, and blue component values.  Each component value should be a number from 0-255 where 0 is the lowest intensity and 255 is the highest intensity.
  • show() - This function is very important because it's the only function that will actually change the color of the LEDs.  After you've set pixel colors you must call show() to update the hardware!

I'll skip describing the rest of the animation functions since they're pretty similar in their usage of the NeoPixel library.

# Create NeoPixel object with appropriate configuration.
strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT)
# Intialize the library (must be called once before other functions).
strip.begin()

Further down in the example code you'll find the lines above which create the Adafruit_NeoPixel object.  The initializer function for this object takes in all the parameters defined earlier like the number of pixels, GPIO pin connected to the pixels, etc.  

Notice that after creating the Adafruit_NeoPixel object the begin() function is called.  It's very important to call begin() once before you make other calls on the Adafruit_NeoPixel object!

print 'Press Ctrl-C to quit.'
while True:
	# Color wipe animations.
	colorWipe(strip, Color(255, 0, 0))  # Red wipe
	colorWipe(strip, Color(0, 255, 0))  # Blue wipe
	colorWipe(strip, Color(0, 0, 255))  # Green wipe
	# Theater chase animations.
	theaterChase(strip, Color(127, 127, 127))  # White theater chase
	theaterChase(strip, Color(127,   0,   0))  # Red theater chase
	theaterChase(strip, Color(  0,   0, 127))  # Blue theater chase
	# Rainbow animations.
	rainbow(strip)
	rainbowCycle(strip)
	theaterChaseRainbow(strip)

The final part of the example enters a loop where it calls the animation functions defined earlier.  The important thing to notice here is how a color is defined with the Color() function.  This function takes 3 parameters, the red, green, and blue component values of the color.  Each component is a value from 0-255 where 0 is the lowest intensity and 255 is the highest intensity.

For example to generate the brightest red color possible you would call Color(255, 0, 0).  Or to generate a moderately pink color you could call Color(128, 0, 128).

That's all there is to using the NeoPixel Python wrapper around the rpi_ws281x library!

If you'd like to see all the functions available in the library, run the command:

pydoc neopixel

For reference here's the full output of the pydoc command:

Help on module neopixel:

NAME
    neopixel

DESCRIPTION
    # Adafruit NeoPixel library port to the rpi_ws281x library.
    # Author: Tony DiCola ([email protected])

CLASSES
    __builtin__.object
        Adafruit_NeoPixel
    
    class Adafruit_NeoPixel(__builtin__.object)
     |  Methods defined here:
     |  
     |  __del__(self)
     |  
     |  __init__(self, num, pin, freq_hz=800000, dma=5, invert=False)
     |      Class to represent a NeoPixel/WS281x LED display.  Num should be the
     |      number of pixels in the display, and pin should be the GPIO pin connected
     |      to the display signal line (must be a PWM pin like 18!).  Optional
     |      parameters are freq, the frequency of the display signal in hertz (default
     |      800khz), dma, the DMA channel to use (default 5), and invert, a boolean
     |      specifying if the signal line should be inverted (default False).
     |  
     |  begin(self)
     |      Initialize library, must be called once before other functions are
     |      called.
     |  
     |  getPixelColor(self, n)
     |      Get the 24-bit RGB color value for the LED at position n.
     |  
     |  getPixels(self)
     |      Return an object which allows access to the LED display data as if 
     |      it were a sequence of 24-bit RGB values.
     |  
     |  numPixels(self)
     |      Return the number of pixels in the display.
     |  
     |  setBrightness(self, brightness)
     |      Scale each LED in the buffer by the provided brightness.  A brightness
     |      of 0 is the darkest and 255 is the brightest.  Note that scaling can have
     |      quantization issues (i.e. blowing out to white or black) if used repeatedly!
     |  
     |  setPixelColor(self, n, color)
     |      Set LED at position n to the provided 24-bit color value (in RGB order).
     |  
     |  setPixelColorRGB(self, n, red, green, blue)
     |      Set LED at position n to the provided red, green, and blue color.
     |      Each color component should be a value from 0 to 255 (where 0 is the
     |      lowest intensity and 255 is the highest intensity).
     |  
     |  show(self)
     |      Update the display with the data from the LED buffer.
     |  

FUNCTIONS
    Color(red, green, blue)
        Convert the provided red, green, blue color to a 24-bit color value.
        Each color component should be a value 0-255 where 0 is the lowest intensity
        and 255 is the highest intensity.

If you run into issues with the library, try asking for help on the Adafruit forums or even open a bug on the library's home on github.

Last updated on 2015-05-04 at 04.27.56 PM Published on 2014-09-12 at 12.50.09 PM