Skip to main content

WS2812 LED Control (neopixel)

The Firefly T1 drives WS2812 / WS2812B LED strips through the top 5P-PIN expansion header: the data line goes to PIN5 (GPIO13), and 5V comes from PIN1, switched by a P-MOS controlled through GPIO43. The firmware ships two drivers — the generic neopixel library and the built-in ws2812 C module (the official light-painting app uses the latter).

Data line on GPIO13

It is PIN5 on the top 5P-PIN header, wired straight to the MCU — no extra parts needed.

5V needs three things at once

pm.VCC_OUTPUT + pulling GPIO43 low + the data line connected. Miss one and the strip stays dark.

Both drivers work

neopixel is simple and generic; ws2812 uses RMT and refreshes a whole strip or frame faster.

Hardware and Pins​

ItemValue
LED typeWS2812 / WS2812B (5V supply, single-wire 800 kHz timing)
Data pinGPIO13 (PIN5 on the top 5P-PIN header)
Power switchGPIO43 drives a P-MOS: value(0) pulls low and connects, value(1) is high-impedance and cuts it off
5V sourcePIN1 on the top 5P-PIN header; the rail is set by Power Management (pm) VCC
LED countThe official app reserves a maximum of 480
Data layoutLED timing is GRB; the ws2812 buffer is ordered B, G, R
Available driversneopixel (standard library, frozen into the firmware), ws2812 (built-in C module, hard-wired to GPIO13 + RMT channel 0)

Wiring and header pinout are covered in Expansion Interface.

Quick Start​

For the strip to light up, power and data must both be in place:

import pm
pm.init()
pm.set_power_state(pm.VCC_OUTPUT) # make VCC output 5V (the launcher's poll thread applies it within a second)

from machine import Pin
enable_pin = Pin(43, Pin.OPEN_DRAIN)
enable_pin.value(0) # pull low to turn on the P-MOS, 5V appears on PIN1

import neopixel
np = neopixel.NeoPixel(Pin(13), 60) # data pin GPIO13, 60 LEDs

np[0] = (255, 0, 0) # LED 0: red
np[1] = (0, 255, 0) # LED 1: green
np[2] = (0, 0, 255) # LED 2: blue
np.write() # required — colors only go out when you call this

What you'll see: the first three LEDs light up red, green, and blue respectively; the rest stay dark. If you skip np.write(), nothing happens at all — setting colors only changes the buffer in memory.

When running standalone (your own main.py, or straight in the REPL), you also need to call pm.poll() periodically, otherwise set_power_state() never takes effect. See Power Management (pm).

Choosing Between the Two Drivers​

neopixelws2812 (built into firmware)
ImplementationStandard MicroPython driver, pure Python + machine.bitstreamC module using the ESP32 RMT peripheral
Data pinYou pass it, e.g. Pin(13)Fixed to GPIO13, nothing to pass
Setting colorsnp[i] = (R, G, B) tupleYou maintain a bytearray ordered B, G, R
Built-in brightnessNone — scale the RGB values yourselfplay_rgb_buffer() takes a brightness argument
Update granularityChange one LED, then write()Whole-segment refresh only (sends length bytes at once)
Best forFew LEDs, per-LED color changes, simplest codeMany LEDs, full-frame refresh (the official app pushes a full image every second)
LifecycleJust construct itRequires paired init() / deinit()

Recommendation: get your effect working with neopixel first; switch to ws2812 when the LED count grows and the frame rate is no longer enough.

API Reference​

neopixel​

Constructor: NeoPixel()​

np = neopixel.NeoPixel(pin, n, bpp=3, timing=1)
ParameterTypeDefaultDescription
pinPinrequiredData pin, use Pin(13)
nintrequiredNumber of LEDs
bppint3Bytes per LED; 3 for WS2812
timingint11 = 800 kHz (WS2812B standard), 0 = 400 kHz

The constructor immediately sets the pin to output and allocates an n × bpp byte buffer. Matching n to your actual LED count is the safest choice: if it is too small, the trailing LEDs keep whatever color they had before; if it covers more (like the official app's 480), nothing breaks — the extra bytes are simply sent and ignored.

Setting a color: np[i]​

np[0] = (255, 0, 0)
ItemTypeValue
Index iint0 to len(np) - 1; out of range raises IndexError
Valuetuple / list(R, G, B), each component 0 to 255

Reading np[i] back returns exactly the (R, G, B) tuple you wrote.

Filling all LEDs: np.fill()​

np.fill((255, 0, 0)) # set the whole strip to one color

It accepts a single tuple argument. Writing np.fill(255, 0, 0) raises TypeError.

Output: np.write()​

np.write()

Sends the buffer to the strip using 800 kHz timing, blocking until it finishes. Each LED takes about 30 microseconds, so 60 LEDs take about 1.8 ms and 480 LEDs about 14 ms.

LED count: len(np)​

for i in range(len(np)):
np[i] = ...

ws2812 (built into firmware)​

This driver only exposes whole-segment refresh; backed by RMT hardware, it suits refreshing a full strip or a full frame.

Initialization: ws2812.init()​

ws2812.init()

Takes no arguments. It always uses GPIO13 and RMT channel 0, and configures GPIO13 as the RMT output.

Call it once per program. Calling it again without deinit() hits an assert because the RMT channel is already in use, and the device reboots.

Sending RGB888 data: ws2812.play_rgb_buffer()​

ws2812.play_rgb_buffer(buffer, length, brightness)
ParameterTypeDescription
bufferbytearrayRGB888 data, 3 bytes per LED, ordered B, G, R
lengthintNumber of bytes to send; should be a multiple of 3; exceeding the buffer length raises ValueError: Buffer length mismatch
brightnessfloat0.0 to 1.0; out of range raises ValueError: Brightness must be between 0.0 and 1.0

No return value. It does three things:

  1. Multiplies every component by brightness to dim the whole strip (brightness=0 is fully dark);
  2. Reorders the data into the GRB order the LEDs expect and sends it at 800 kHz;
  3. Blocks until everything has been sent (about 30 microseconds per LED, so about 14 ms for 480 LEDs).

You pass neither a pin nor an LED count — the count is length ÷ 3, so a single buffer can be sent out in pieces. That is exactly how the official light-painting app sends one row of an image at a time.

Progress string: ws2812.calculate_percentage()​

text = ws2812.calculate_percentage(20, 48, 13) # → "41% 13s"

Takes three ints (numerator, denominator, seconds) and returns a string of the form "<percent>% <seconds>s". This is a small helper the official app uses to show progress on screen; a denominator of 0 raises ValueError.

Releasing resources: ws2812.deinit()​

ws2812.deinit()

Releases the RMT channel. Call it before your app exits, otherwise the next init() reboots the device.

Colors and Byte Order​

The two drivers use different color orders, and this is the easiest thing to get wrong when switching between them:

Colorneopixel (tuple, R/G/B)ws2812 buffer (bytes, B/G/R)
Rednp[i] = (255, 0, 0)bytearray([0, 0, 255])
Greennp[i] = (0, 255, 0)bytearray([0, 255, 0])
Bluenp[i] = (0, 0, 255)bytearray([255, 0, 0])
Whitenp[i] = (255, 255, 255)bytearray([255, 255, 255])
  • neopixel uses the intuitive (R, G, B) order and converts it to the GRB order the LEDs need internally.
  • The ws2812 buffer is B, G, R, matching the byte layout of BMP image files — which is why the official app can read BMP data straight into the buffer and send it. Writing R, G, B instead shows up as red and blue swapped.

Common Pitfalls​

  1. Forgetting np.write(). Setting colors only changes the in-memory buffer; without write() the LEDs never change.
  2. When nothing lights up, check the three power items: pm.set_power_state(pm.VCC_OUTPUT), enable_pin.value(0), and the data line on PIN5 (GPIO13).
  3. The two GPIO43 states are easy to mix up: value(0) is the connected state (low level turns on the P-MOS), while value(1) is high-impedance and cuts it off. The launcher leaves it cut off while browsing the app list.
  4. The ws2812 buffer order is B, G, R, not R, G, B.
  5. RGB components must stay within 0 to 255 — writing 256 raises ValueError, and an out-of-range index raises IndexError.
  6. np.fill() takes exactly one tuple: np.fill((255, 0, 0)).
  7. ws2812.init() and ws2812.deinit() must be paired. init() uses an ESP_ERROR_CHECK assert internally, so re-initializing reboots the device.
  8. Both write() and play_rgb_buffer() block. More LEDs means longer waits (about 30 microseconds each) — don't set the LED count larger than you need.

More Recipes​

Rainbow gradient​

import neopixel
from machine import Pin
import time

NUM_LEDS = 60
np = neopixel.NeoPixel(Pin(13), NUM_LEDS)


def wheel(pos):
"""Map 0-255 to a rainbow color, returning (R, G, B)."""
pos = pos & 255
if pos < 85:
return (255 - pos * 3, pos * 3, 0)
elif pos < 170:
pos -= 85
return (0, 255 - pos * 3, pos * 3)
else:
pos -= 170
return (pos * 3, 0, 255 - pos * 3)


offset = 0
while True:
for i in range(NUM_LEDS):
np[i] = wheel(i * 256 // NUM_LEDS + offset)
np.write()
offset = (offset + 4) & 255
time.sleep_ms(20)

Dimming everything (neopixel has no brightness argument)​

Scale every component proportionally:

BRIGHT = 0.25 # 0.0 to 1.0


def dim(color):
return tuple(int(c * BRIGHT) for c in color)


np.fill(dim((255, 0, 0))) # dim red
np.write()

With many LEDs and a tight power budget, holding brightness at 0.2 to 0.3 cuts current draw noticeably.

Breathing effect with ws2812 (built-in brightness)​

import ws2812
import math
import time

NUM_LEDS = 30
ws2812.init()

buf = bytearray([0, 0, 255] * NUM_LEDS) # pure red: B=0, G=0, R=255

step = 0
while True:
level = (math.sin(step / 20.0) + 1) / 2 # 0.0 to 1.0
ws2812.play_rgb_buffer(buf, len(buf), level)
step += 1
time.sleep_ms(30)

Complete Example​

Firefly T1 apps live on the SD card under /sd/apps/<app-folder>/, with boot.py as the entry point. Put the following into /sd/apps/my-light-app/boot.py: up / down short press cycles colors, center short press toggles brightness, and a center long press exits and turns the strip off.

import pm
import neopixel
import time
from machine import Pin
from button import Button

NUM_LEDS = 60
COLORS = [(255, 0, 0), (0, 255, 0), (0, 0, 255)] # red / green / blue
NAMES = ['red', 'green', 'blue']

index = 0
brightness = 0.5
running = True
dirty = True

# Three things for power: VCC output + P-MOS on + data line on PIN5 (GPIO13)
pm.init()
pm.set_power_state(pm.VCC_OUTPUT) # the launcher's poll thread applies it within a second

enable_pin = Pin(43, Pin.OPEN_DRAIN)
enable_pin.value(0) # pull low to turn on the P-MOS, 5V appears on PIN1

np = neopixel.NeoPixel(Pin(13), NUM_LEDS)
buttons = Button()


def on_up():
global index, dirty
index = (index - 1) % len(COLORS)
dirty = True


def on_down():
global index, dirty
index = (index + 1) % len(COLORS)
dirty = True


def on_center_short():
global brightness, dirty
brightness = 0.2 if brightness > 0.5 else 0.9 # toggle between two levels
dirty = True


def on_center_long():
global running
running = False


buttons.register_callback('up', 'short', on_up)
buttons.register_callback('down', 'short', on_down)
buttons.register_callback('center', 'short', on_center_short)
buttons.register_callback('center', 'long', on_center_long)

while running:
if dirty: # refresh only on change to save time
dirty = False
np.fill(tuple(int(c * brightness) for c in COLORS[index]))
np.write()
print("{} brightness {}".format(NAMES[index], brightness))
time.sleep(0.05)

np.fill((0, 0, 0)) # turn the strip off before exiting
np.write()
enable_pin.value(1) # high-impedance, cut the 5V output (same as the launcher)
buttons.deinit()

Related modules: 5-Way Button (button), Power Management (pm), and Microphone (mic).

Troubleshooting​

SymptomCause / Fix
Strip stays completely darkOne of the three power items is missing → check pm.VCC_OUTPUT, enable_pin.value(0), and that the data line is on PIN5 (GPIO13)
Changed np[i] but nothing happensMissing np.write() → every change takes effect only after write()
Red and blue are swappedWith ws2812.play_rgb_buffer() the buffer was written as R, G, B → use B, G, R
Only the first few LEDs light upn in NeoPixel(Pin(13), n) is too small → match the real LED count, or pass an upper bound
IndexError raisedIndex i in np[i] is out of range → valid range is 0 to len(np) - 1
ValueError: byte must be in range(0, 256)An RGB component exceeds 255 → keep each within 0 to 255
np.fill() raises TypeErrorWritten as np.fill(255, 0, 0) → pass one tuple: np.fill((255, 0, 0))
ValueError: Brightness must be between 0.0 and 1.0brightness was given as 0-255 → use a float from 0.0 to 1.0
Device reboots as soon as ws2812.init() is calledA previous run never called ws2812.deinit(), so the RMT channel is still taken → deinit() first, then init()
Colors look washed out, far end flickersInsufficient 5V current or too long a data line → power closer to the strip, shorten the data wire, or lower brightness

AI Usage (Coming Soon)​

Soon you won't have to reason about the two GPIO43 states or remember the BGR order: describe the lighting effect you want in plain language, and the Agent will use the APIs in this document to generate a complete program that runs on the Firefly T1.

For example, just tell it:

60 LEDs. On startup, sweep a rainbow out from the middle toward both ends, then hold it steady. Center short press toggles brightness; long press exits and turns the strip off.

It will combine neopixel, pm, and Button into a runnable program and place it under /sd/apps/ on the SD card.

Agent entry (coming soon)

The entry link will go here. Once it is live, one click takes you straight to describing the app you want.