Skip to main content

LED Control (WS2812 / neopixel)

The Beetle S1's LED strip data line is fixed at GPIO13, and the firmware ships two ways to drive it: ws2812 (a C module using the RMT hardware, with a brightness parameter — this is what the light painting apps use) and neopixel (built into MicroPython, the shortest syntax). Both drive the same wire, so pick one.

Two ways to light up

ws2812 pushes a whole strip at once and scales brightness for you; neopixel sets one pixel per line.

Data line hardwired to GPIO13

The pin is fixed in firmware (routed to an XT30 signal pin) and cannot be changed in software.

Brightness only in ws2812

neopixel has no brightness argument — scale the RGB values yourself.

Hardware and wiring​

ItemValue
Data lineGPIO13 (fixed, not configurable)
Driver pathws2812 → RMT channel 0 (installed once, kept alive); neopixel → built-in bitstream (installs a channel on every write())
Wire format24 bits per LED, sent in G → R → B order
LEDs per transmissionUp to 480 (same as the light painting app's MAX_RESOLUTION)
PowerXT30 output port, direct 3S Li-ion voltage (about 9–12.6V)

For strip selection and how to wire it to the XT30 port, see Compatible LEDs & Wiring.

LED count comes from the config​

Beetle S1 apps share one convention: LED count = light_stick_length (number of segments) in /sd/apps/config.json × 48. The default 3 gives 144 LEDs.

import ujson

try:
with open('/sd/apps/config.json') as f:
n = ujson.load(f).get('light_stick_length', 3) * 48
except (OSError, ValueError):
n = 144 # fall back to the default

That way, when a user changes the segment count in the config, your effect length follows automatically without code changes.

Quick start​

import ws2812

ws2812.init() # install the RMT channel, call once per program

N = 144 # 144 LEDs
buf = bytearray(N * 3) # 3 bytes per LED, in order: blue, green, red
for i in range(N):
buf[i * 3 + 2] = 255 # write to the "red" slot -> the whole strip turns red

ws2812.play_rgb_buffer(buf, len(buf), 0.5) # args: buffer, byte count, brightness (0.0-1.0)

What you'll see: the whole strip lights up red at 50% brightness. Brightness is a multiplier, so 255 × 0.5 ≈ 128.

With neopixel (shortest syntax)​

import neopixel
from machine import Pin

np = neopixel.NeoPixel(Pin(13), 144) # 144 LEDs
np[0] = (255, 0, 0) # first LED red (order: red, green, blue)
np[10] = (0, 0, 255) # 11th LED blue
np.write() # nothing changes on the strip until write() is called

What you'll see: LED 1 red, LED 11 blue, the rest unchanged (usually off after power-up).

Which one should you use?​

ws2812 (C module)neopixel (built in)
Unit of transmissionThe whole strip (bytearray + byte count)The whole strip (assign per LED, then write())
Brightness argumentYes, the 3rd argument of play_rgb_buffer()No, scale the RGB yourself
Buffer color orderBlue, green, red (BGR)Tuple order is red, green, blue (RGB)
Refresh costChannel stays installed, good for high frame ratesInstalls and uninstalls an RMT channel on every write()
Typical useRow-by-row light painting playback, whole-strip animationA few LEDs, simple status indication

The light painting apps use ws2812 for exactly this reason: the channel stays installed, so high-frequency refresh is more stable — one row per frame has to keep up with the camera.

API reference​

ws2812 (C module)​

ws2812.init()​

ws2812.init()

No arguments, no return value. Configures RMT channel 0 on GPIO13 and installs the driver.

  • Call it once per program: the same RMT channel can only be installed once, and a second call raises an error.
  • You must init() before play_rgb_buffer(), otherwise the channel is not installed and transmission fails.

ws2812.play_rgb_buffer(buffer, length, brightness)​

ws2812.play_rgb_buffer(buffer, length, brightness)
ArgumentTypeDescription
bufferbytearray / bytesRGB data, 3 bytes per LED, in blue, green, red order
lengthintNumber of bytes to send (not LED count); normally len(buffer)
brightnessfloatBrightness factor, 0.0–1.0; 0 = off, 1.0 = full color

No return value. The call blocks until transmission finishes, so its return also means "this frame is on the wire."

  • length larger than the buffer's real size → ValueError: Buffer length mismatch.
  • brightness outside 0.0–1.0 → ValueError: Brightness must be between 0.0 and 1.0.
  • LED count = length // 3; trailing bytes that do not fill an LED are ignored.
  • Color conversion: it reads buffer[+2] as red, [+1] as green and [+0] as blue, then shifts out in G→R→B order — exactly what WS2812 / WS2815 expect.

ws2812.calculate_percentage(numerator, denominator, seconds)​

text = ws2812.calculate_percentage(row, total_rows, elapsed_seconds)
# e.g. returns "45% 3s"

Returns a string of the form "percentage% seconds s". It is just a small formatting helper (the light painting app prints progress on screen) and has nothing to do with the strip itself.

  • denominator of 0 → ValueError: Denominator cannot be zero.
  • The percentage uses integer division and is not rounded.

ws2812.deinit()​

ws2812.deinit()

No arguments, no return value. Uninstalls RMT channel 0.

Note: uninstalling the channel does not turn the LEDs off — the strip keeps the last color it received. To actually go dark, send one all-zero frame first, then deinit():

ws2812.play_rgb_buffer(bytearray(144 * 3), 144 * 3, 0)
ws2812.deinit()

neopixel (built into MicroPython)​

neopixel.NeoPixel(pin, n[, bpp])​

import neopixel
from machine import Pin

np = neopixel.NeoPixel(Pin(13), 144)
ArgumentTypeDefaultDescription
pinPin—Data line; on the Beetle S1 this is Pin(13)
nint—Number of LEDs
bppint3Bytes per LED; 3 for regular RGB strips, 4 for RGBW strips

Returns the strip object. Constructing it sends no data.

np[i] = (r, g, b) and np.fill((r, g, b))​

np[0] = (255, 0, 0) # first LED
np.fill((0, 0, 0)) # set the whole strip at once

Each item is an integer 0–255 in red, green, blue order. Assignment only changes memory, not the strip.

np.write()​

np.write()

Actually pushes the colors in memory to the strip. No arguments, no return value.

Every call installs and uninstalls an RMT channel, so keep it out of very tight loops — when you need fast row-by-row refresh, use ws2812.play_rgb_buffer().

len(np)​

len(np) # number of LEDs

Colors and byte order (the biggest trap)​

The two interfaces take their arguments in different orders, which is the most common source of bugs:

InterfaceOrder you writeHow
ws2812.play_rgb_bufferBlue, green, red (BGR)buf[i*3+0]=blue, +1=green, +2=red
neopixel.NeoPixelRed, green, blue (RGB)np[i] = (red, green, blue)

Why is ws2812 BGR? Because in a 24-bit BMP file pixels are already stored as B, G, R — that lets the light painting app hand a whole BMP row straight to the driver with no conversion at all.

The driver then sends in GRB order on the wire (what WS2812 / WS2815 require). If red and green are swapped on your strip:

  • set "red_green_swap" to true in /sd/apps/config.json (the app then swaps the green and red slots in the buffer for you), or
  • swap the green and red slots yourself when filling the buffer.

Common pitfalls​

SymptomCause / fix
Strip completely darkneopixel without write(); or ws2812 without init(); or the strip has no power
Red and green swappedStrip color order differs from the driver → red_green_swap: true
Colors off overall (looks like blue/red swapped)Wrong buffer order: ws2812 wants BGR, neopixel wants RGB
Only the first few LEDs light, then garbagelength was given the LED count instead of the byte count
ValueError: Buffer length mismatchlength is larger than the buffer's real size
Changing brightness does nothingYou are using neopixel (no brightness argument) → use ws2812 or scale RGB yourself
Second ws2812.init() raises an errorRMT channel 0 can only be installed once → call init() once for the whole program
LEDs stay lit after deinit()Uninstalling ≠ turning off → send one all-zero frame first
Frame rate too low, flickeringYou refresh per frame with neopixel.write() → switch to ws2812.play_rgb_buffer()

More recipes​

Rainbow sweep​

import ws2812
import time

N = 144
buf = bytearray(N * 3)
offset = 0

def wheel(pos):
"""0-255 position -> (red, green, blue)"""
pos = pos % 255
if pos < 85:
return (pos * 3, 255 - pos * 3, 0)
if pos < 170:
pos -= 85
return (255 - pos * 3, 0, pos * 3)
pos -= 170
return (0, pos * 3, 255 - pos * 3)

ws2812.init()
try:
while True:
for i in range(N):
r, g, b = wheel(i * 256 // N + offset)
buf[i * 3 + 0] = b # blue
buf[i * 3 + 1] = g # green
buf[i * 3 + 2] = r # red
ws2812.play_rgb_buffer(buf, len(buf), 0.4)
offset = (offset + 4) % 255
time.sleep(0.02) # about 50 fps
finally:
ws2812.play_rgb_buffer(bytearray(N * 3), N * 3, 0)
ws2812.deinit()

Breathing light (using ws2812's brightness)​

import ws2812
import math
import time

N = 144
buf = bytearray(N * 3)
for i in range(N):
buf[i * 3 + 0] = 255 # blue

ws2812.init()
try:
step = 0
while True:
level = (math.sin(step / 12) + 1) / 2 # 0.0 ~ 1.0
ws2812.play_rgb_buffer(buf, len(buf), level)
step += 1
time.sleep(0.03)
finally:
ws2812.play_rgb_buffer(buf, len(buf), 0)
ws2812.deinit()

neopixel has no brightness argument, so the same effect has to be scaled by hand: np[i] = (int(r * level), int(g * level), int(b * level)).

A few status LEDs with neopixel​

import neopixel
from machine import Pin

np = neopixel.NeoPixel(Pin(13), 3) # use just the first 3 LEDs as indicators

def status(state):
np.fill((0, 0, 0))
if state == 'ok':
np[0] = (0, 255, 0)
elif state == 'busy':
np[1] = (255, 160, 0)
else:
np[2] = (255, 0, 0)
np.write()

Complete example​

Save this as /sd/apps/led-demo/boot.py on the SD card: it runs a rainbow on boot, up/down adjust brightness, and a long press of center exits.

import ws2812
import time
from button import Button

N = 144
buf = bytearray(N * 3)
brightness = 0.4
offset = 0
running = True

def wheel(pos):
pos = pos % 255
if pos < 85:
return (pos * 3, 255 - pos * 3, 0)
if pos < 170:
pos -= 85
return (255 - pos * 3, 0, pos * 3)
pos -= 170
return (0, pos * 3, 255 - pos * 3)

def on_up():
global brightness
brightness = min(1.0, round(brightness + 0.1, 2))

def on_down():
global brightness
brightness = max(0.0, round(brightness - 0.1, 2))

def on_exit():
global running
running = False

ws2812.init()
buttons = Button()
buttons.register_callback('up', 'short', on_up)
buttons.register_callback('down', 'short', on_down)
buttons.register_callback('center', 'long', on_exit)

try:
while running:
for i in range(N):
r, g, b = wheel(i * 256 // N + offset)
buf[i * 3 + 0] = b # blue
buf[i * 3 + 1] = g # green
buf[i * 3 + 2] = r # red
ws2812.play_rgb_buffer(buf, len(buf), brightness)
offset = (offset + 4) % 255
time.sleep(0.03)
finally:
ws2812.play_rgb_buffer(bytearray(N * 3), N * 3, 0) # go dark first
buttons.deinit()
ws2812.deinit()

One detail worth noting: play_rgb_buffer() blocks until the frame is out, so the main loop needs no extra synchronization.

Troubleshooting​

SymptomCause / fix
Nothing happens at allCheck strip power first (XT30 gives 3S voltage directly; a 5V strip needs a 12V→5V module), then confirm you called init() / write()
Only a short section lightslength does not match the real LED count → pass len(buf)
Colors jump around randomlyData and clock lines swapped, or the strip's DIN is wired to the wrong end (most strips are directional)
First LED flickersData line too long or unshielded, or the strip and controller are not sharing ground → shorten the cable and make sure ground is common
Very dim outputbrightness is too low; or the strip itself is underpowered (long strips need their own supply)
ValueError: Brightness must be between 0.0 and 1.0Brightness was passed as an integer like 0–255 → use a float 0.0–1.0
Memory error after running a whileEach ws2812 transmission allocates LED count × 24 RMT entries temporarily → lower the LED count or the refresh rate
Garbled strip when used with light paintingTwo code paths writing GPIO13 at once → keep only one driver instance active at a time

Related modules: Button Control (button) · Buzzer (beep) · Display (ST7789)

AI usage (coming soon)​

Soon you won't need to work out BGR order or the rainbow algorithm yourself: describe the lighting effect you want in plain language, and the Agent will follow the APIs in this page to generate a complete program that runs on the Beetle S1.

For example, just say:

On boot, run a rainbow on the strip; up brightens, down dims, a long press of center exits, and turn the strip off before exiting.

It will combine ws2812, the LED count from config.json and the button callbacks into a working program, and place it in /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.