【得捷电子Follow me第2期】 任务3:控制WS2812B
[复制链接]
本帖最后由 knv 于 2023-10-10 09:49 编辑
【得捷电子Follow me第2期】 任务3:控制WS2812B
0x0:准备好板卡链接。导入控制RGB灯的库 adafruit_ws2801.py
板子的RGB灯为
board.NEOPIXEL
只需要使用neopixel库,进行RGB控制该设备即可
按键切换灯颜色,首先创建一个颜色列表,将 颜色RGB值定义
colors = [(0x00, 0x00, 0x00), # black
(0xFF, 0x00, 0x00), # red
(0x00, 0xFF, 0x00), # green
(0x00, 0x00, 0xFF), # blue
(0xFF, 0xFF, 0xFF)] # white
创建一个循环,监听按键事件,若按下则颜色+1,采用color 的颜色,这样缩减了代码的大小,使程序逻辑更清晰
屏幕同时显示对应的颜色文字,与之前的显示中文代码类似,不再赘述
0x1:其中代码如下
import time
import board
import neopixel
import digitalio
from adafruit_display_text import bitmap_label
from adafruit_bitmap_font import bitmap_font
# Load the font
font = bitmap_font.load_font("font/DingTalk_ncn_60.pcf")
# Define colors
colors = [(0x00, 0x00, 0x00), # black
(0xFF, 0x00, 0x00), # red
(0x00, 0xFF, 0x00), # green
(0x00, 0x00, 0xFF), # blue
(0xFF, 0xFF, 0xFF)] # white
# Initialize NeoPixel
pixel = neopixel.NeoPixel(board.NEOPIXEL, 1)
pixel.brightness = 0.5
# Initialize the button
button = digitalio.DigitalInOut(board.BUTTON)
button.switch_to_input(pull=digitalio.Pull.UP)
# Initialize text label
text_area = bitmap_label.Label(font, scale=1)
text_area.x = 0
text_area.y = 60
current_color_index = -1
while True:
# Read the button state
button_state = not button.value
if button_state:
# Cycle through colors
current_color_index = (current_color_index + 1) % len(colors)
pixel.fill(colors[current_color_index])
# Set the text and color
text2 = ["black", "red", "green", "blue", "white"][current_color_index]
text_area.text = text2
text_area.color = colors[current_color_index]
board.DISPLAY.show(text_area)
time.sleep(0.1)
显示效果如下:
QQ视频20231009222545
|