Skip to content

MicroPython: NeoPixels

Leo Vidarte edited this page Mar 14, 2017 · 13 revisions

NeoPixels, also known as WS2812b 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.

To create a NeoPixel object do the following:

>>> from machine import Pin
>>> from neopixel import NeoPixel
>>> np = NeoPixel(Pin(14), 8)

This configures a NeoPixel strip on GPIO14 with 8 pixels. You can adjust the “14” (pin number) and the “8” (number of pixels) to suit your set up.

>>> for i, pixel in enumerate(np):
...     print(i, pixel)
...     
...     
... 
0 (0, 0, 0)
1 (0, 0, 0)
2 (0, 0, 0)
3 (0, 0, 0)
4 (0, 0, 0)
5 (0, 0, 0)
6 (0, 0, 0)
7 (0, 0, 0)

To set the colour of pixels use:

>>> np[0] = (255, 0, 0) # set to red, full brightness
>>> np[1] = (0, 128, 0) # set to green, half brightness
>>> np[2] = (0, 0, 64)  # set to blue, quarter brightness

Then use the write() method to output the colours to the LEDs:

>>> np.write()

To set a random color you can use the getrandbits() function

>>> from urandom import getrandbits
>>> for i in np.n:
...     np[i] = (getrandbits(8), getrandbits(8), getrandbits(8))
...     
...     
... 
>>> np.write()

The following demo function makes a fancy show on the LEDs:

https://github.com/lvidarte/esp8266/blob/master/examples/neopixel/src/python/main.py