MicroPythonRaspberry Pi PicoExact chip

MicroPython: PIO, a WS2812 driver in four instructions

A PIO program written in Python drives a 16-pixel ring: the RP2040’s own state machine shifts out every bit.

MicroPython: PIO, a WS2812 driver in four instructions in Argynix Lab

The code

main.pyPython
# The RP2040's PIO: a state machine runs this four-instruction program, shifting each
# 24-bit colour out on GP16 with WS2812 timing (8 MHz, 10 cycles a bit). The CPU only
# hands it words.
import array, time
from machine import Pin
import rp2

@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=24)
def ws2812():
    T1, T2, T3 = 2, 5, 3
    wrap_target()
    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]
    wrap()

sm = rp2.StateMachine(0, ws2812, freq=8_000_000, sideset_base=Pin(16))
sm.active(1)
pixels = array.array("I", [0] * 16)

def grb(r, g, b):
    return (g << 16) | (r << 8) | b

step = 0
while True:
    for i in range(16):
        on = (i + step) % 16 < 4
        pixels[i] = grb(0, 40 + 12 * i, 160) if on else grb(0, 0, 0)
    sm.put(pixels, 8)
    step += 1
    time.sleep(0.08)