12. 控制 APA102 LED¶
APA102 LED,也称为 DotStar LED,是可单独寻址的全彩 RGB LED,通常呈串状。它们与 NeoPixels 的不同之处在于它们需要两个引脚来控制——时钟和数据引脚。它们可以在比 NeoPixels 更高的数据和 PWM 频率下运行,并且更适合视觉暂留效果。
要创建 APA102 对象,请执行以下操作:
>>> import machine, apa102
>>> strip = apa102.APA102(machine.Pin(5), machine.Pin(4), 60)
这将配置一个 60 像素的 APA102 条带,其时钟位于 GPIO5 上,数据位于 GPIO4 上。您可以调整引脚数和像素数以满足您的需要。
RGB 颜色数据以及亮度级别按特定顺序发送到 APA102。通常这是. 如果您使用的是较新的 APA102C LED 之一,则绿色和蓝色会交换,因此顺序为。APA102 有更多的方形镜头,而 APA102C 有更多的圆形镜头。如果您使用的是 APA102C 条带并且更喜欢以 RGB 顺序而不是 RBG 提供颜色,您可以像这样自定义元组颜色顺序:(Red, Green, Blue, Brightness)
(Red, Blue, Green, Brightness)
>>> strip.ORDER = (0, 2, 1, 3)
要设置像素的颜色,请使用:
>>> strip[0] = (255, 255, 255, 31) # set to white, full brightness
>>> strip[1] = (255, 0, 0, 31) # set to red, full brightness
>>> strip[2] = (0, 255, 0, 15) # set to green, half brightness
>>> strip[3] = (0, 0, 255, 7) # set to blue, quarter brightness
使用该write()
方法将颜色输出到 LED:
>>> strip.write()
示范:
import time
import machine, apa102
# 1M strip with 60 LEDs
strip = apa102.APA102(machine.Pin(5), machine.Pin(4), 60)
brightness = 1 # 0 is off, 1 is dim, 31 is max
# Helper for converting 0-255 offset to a colour tuple
def wheel(offset, brightness):
# The colours are a transition r - g - b - back to r
offset = 255 - offset
if offset < 85:
return (255 - offset * 3, 0, offset * 3, brightness)
if offset < 170:
offset -= 85
return (0, offset * 3, 255 - offset * 3, brightness)
offset -= 170
return (offset * 3, 255 - offset * 3, 0, brightness)
# Demo 1: RGB RGB RGB
red = 0xff0000
green = red >> 8
blue = red >> 16
for i in range(strip.n):
colour = red >> (i % 3) * 8
strip[i] = ((colour & red) >> 16, (colour & green) >> 8, (colour & blue), brightness)
strip.write()
# Demo 2: Show all colours of the rainbow
for i in range(strip.n):
strip[i] = wheel((i * 256 // strip.n) % 255, brightness)
strip.write()
# Demo 3: Fade all pixels together through rainbow colours, offset each pixel
for r in range(5):
for n in range(256):
for i in range(strip.n):
strip[i] = wheel(((i * 256 // strip.n) + n) & 255, brightness)
strip.write()
time.sleep_ms(25)
# Demo 4: Same colour, different brightness levels
for b in range(31,-1,-1):
strip[0] = (255, 153, 0, b)
strip.write()
time.sleep_ms(250)
# End: Turn off all the LEDs
strip.fill((0, 0, 0, 0))
strip.write()