[Digi-Key Follow Me Issue 2] Task 3: Control WS2812B
[Copy link]
[Digi-Key Follow me Issue 2] Task 3: Control WS2812B
WS2812B is a digitally addressable LED (Digital Addressable LED) lamp bead, also known as NeoPixel
This time the task is to control the color change of the only LED on the board through the board's buttons, but the board has two buttons, one is Rst and the other is Boot, so the Boot button is used.
Next, use CircuitPython to switch the lights to different colors by pressing the Boot button.
1. Import the neopixel library and initialize it
2. Initialize the button variable btn
3. Initialize the color array colorArr and the default index you want to loop
4. In the last infinite loop, each click switches the index of the array, which is equivalent to changing the color value. You can also randomly index (randomly change the color)
import time
import board
import digitalio
import neopixel
import random
pixel = neopixel.NeoPixel(board.NEOPIXEL, 1)
# 初始化btn按钮对象
btn = digitalio.DigitalInOut(board.BOOT0)
# 设置btn引脚为输入
btn.direction = digitalio.Direction.INPUT
# 设置btn引脚为上拉
btn.pull = digitalio.Pull.UP
# 红 绿 蓝 黄 白
colorArr = [(255, 0, 0), (0, 255, 0), (0, 0, 255), (255, 255, 0), (255, 255, 255)]
index = 0
while True:
if not btn.value:
# 从colorArr中索引顺序切换颜色
if index == len(colorArr) - 1:
index = 0
else:
index = index+1
# pixel.fill(random.choice(colorArr)) # 从colorArr中随机选择一个颜色
pixel.fill(colorArr[index])
time.sleep(0.5)
else:
# 按键未按下时
pass
|