neopixel --- 控制 WS2812 / NeoPixel LED

本模块为 WS2812 / NeoPixel LED 灯带提供了驱动程序。该驱动依赖 machine.bitstream() 来生成 LED 所需的精确定时信号,因此它可以在任何 machine 模块实现了 bitstream 的移植版本上运行。

应用程序通过项赋值或 NeoPixel.fill() 设置像素数据,然后调用 NeoPixel.write() 来更新灯带。每个像素以用户所接受顺序的 RGB 或 RGBW 元组形式呈现;驱动在内部处理 GRB(W) 线序。

示例:

import machine
import neopixel

# 32 LED strip connected to pin P7.
n = neopixel.NeoPixel(machine.Pin("P7"), 32)

# Draw a red gradient.
for i in range(32):
    n[i] = (i * 8, 0, 0)

# Update the strip.
n.write()

class NeoPixel

class neopixel.NeoPixel(pin: 'machine.Pin', n: int, bpp: int = 3, timing: int | tuple[int, int, int, int] = 1)

为连接到 pin 的一条 LED 灯带构造一个 NeoPixel 对象。

  • pin 是一个 machine.Pin 实例;构造函数会将其重新配置为输出。

  • n 是灯带中 LED 的数量。

  • bpp 是每个像素的字节数:RGB LED(如 WS2812)为 3,RGBW LED(如 SK6812-RGBW)为 4

  • timing 选择位定时。0 选择慢速的 400 kHz 定时,1 选择大多数现代灯带使用的标准 800 kHz 定时。也可以传入一个以纳秒为单位时长的四元组 (high_0, low_0, high_1, low_1),其形式与 machine.bitstream() 所接受的相同。

ORDER: tuple[int, int, int, int]

将面向用户的通道顺序映射到线序的类属性。默认为 (1, 0, 2, 3),即用户提供的 (R, G, B[, W]) 元组将以 G R B [W] 的顺序传输。子类可以重写 ORDER 以支持具有不同线序的灯带。

fill(pixel: tuple[int, ...]) None

将灯带中的每个像素设置为 pixel,即一个取值范围在 0-255 之间的整数 RGB 或 RGBW 元组。

__len__() int

返回灯带中 LED 的数量。

__setitem__(index: int, val: tuple[int, ...]) None

index 处的像素设置为 val,即一个 RGB 或 RGBW 元组。数据仅被缓冲;调用 write() 才会将其推送到灯带。

__getitem__(index: int) tuple[int, ...]

以面向用户的通道顺序,从本地缓冲区返回 index 处的像素,形式为 RGB 或 RGBW 元组。

write() None

使用 machine.bitstream() 将缓冲的像素数据传输到灯带。