Firstly pressed on jalanjalantok.com
Micropython port for ESP8266/ESP32 system has been every intuitive and promote easy access to play with WS2812 led a.k.a neopixel. Here is the snapshot of how easy it is, taken from micropython documentation
from machine import Pin from neopixel import NeoPixel pin = Pin(0, Pin.OUT) # set GPIO0 to output to drive NeoPixels np = NeoPixel(pin, 8) # create NeoPixel driver on GPIO0 for 8 pixels np = (255, 255, 255) # set the first pixel to white np.write() # write data to all pixels r, g, b = np # get first pixel colour
Meanwhile Raspberry Pi Pico took different approach as it done via interface with PIO. Check Pi’s blog page to know more about PIO (link). So it requires more lines of code to get it done. Thus i prepared a wrapper to simplify the process when working with neopixel leds.
import array, time from machine import Pin from rp2 import PIO, StateMachine, asm_pio class NeoPixel: def __init__(self, NUM_LEDS=1,pin=28): @asm_pio(sideset_init=PIO.OUT_LOW, out_shiftdir=PIO.SHIFT_LEFT,autopull=True, pull_thresh=24) def ws2812(): T1 = 2 T2 = 5 T3 = 3 label("bitloop") out(x, 1) .side(0) [T3 - 1] jmp(not_x, "do_zero") .side(1) [T1 - 1] jmp("bitloop") .side(1) [T2 - 1] label("do_zero") nop() .side(0) [T2 - 1] self.num=NUM_LEDS self.sm = StateMachine(0, ws2812, freq=8000000, sideset_base=Pin(pin)) self.sm.active(1) self.ar = array.array("I", [0 for _ in range(self.num)]) def display(self,num=0,color): r,g,b=color self.ar[num]= r<<8 | g<<16 | b self.sm.put(self.ar,8)
We can create a good filename such as neopixel.py and save it in the microcontroller’s flash storage. From this point onwards, the code will be much simpler. To access one neopixel wired to pin 28, we just need to type the following.
from neopixel import NeoPixel np=NeoPixel(NUM_LEDS=1,pin=28) np.display(0,(255,0,0))
Thanks for reading and hope this post is useful. Until next time.