MicroPython: NeoPixels - lvidarte/esp8266 GitHub Wiki

imgs/neopixel.jpg

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.

Schematic

https://raw.githubusercontent.com/lvidarte/esp8266/master/examples/neopixels/neopixels.png

NeoPixel basics

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 range(np.n):
...     np[i] = (getrandbits(8), getrandbits(8), getrandbits(8))
...     
...     
... 
>>> np.write()

Demo

Go to the examples/neopixels/src/python folder and upload the main.py with ampy:

$ bin/ampy --port /dev/ttyUSB0 put main.py

Then go to the python shell, reboot MicroPython with Ctrl-D (to load the main.py file) and run the function demo(pin, n), where pin is the GPIO number and n is the length of pixels in the neopixels array.

$ bin/shell
[Ctrl-D]

PYB: soft reboot
#21 ets_task(40100164, 3, 3fff8398, 4)
could not open file 'boot.py' for reading
MicroPython v1.8.7-7-gb5a1a20a3 on 2017-01-09; ESP module with ESP8266
Type "help()" for more information.
>>> demo(pin=14, n=8)

Resources