【Follow me第二季第1期】基础任务一(必做):控制板载炫彩LED,跑马灯点亮和颜色...
[复制链接]
板载的炫彩LED是WS2812的rgb灯珠在其中我们可以通过调用neopixel库
来实现这个目标可以参考这个官方网站Adafruit CircuitPython NeoPixel — Adafruit CircuitPython NeoPixel Library 1.0 documentation
我们首先需要对灯珠进行初始化
初始化函数定义如下
classneopixel.NeoPixel(pin: Pin, n: int, *, bpp: int = 3, brightness: float = 1.0, auto_write: bool = True, pixel_order: str = None)[source]¶
A sequence of neopixels.
Parameters:
pin (Pin) – The pin to output neopixel data on.
n (int) – The number of neopixels in the chain
bpp (int) – Bytes per pixel. 3 for RGB and 4 for RGBW pixels.
brightness (float) – Brightness of the pixels between 0.0 and 1.0 where 1.0 is full brightness
auto_write (bool) – True if the neopixels should immediately change when set. If False, show must be called explicitly.
pixel_order (str) – Set the pixel color channel order. GRBW is set by default.
但经过查阅资料了解到python已经封装好了无需自己写驱动直接调用即可这里附上详细代码
import time # 导入时间模块
from adafruit_circuitplayground import cp
# 定义颜色映射字典,将颜色名称映射到RGB元组
color_mapping = {
"black": (0, 0, 0), # 黑色
"white": (255, 255, 255), # 白色
"green": (0, 255, 0), # 绿色
"red": (255, 0, 0), # 红色
"blue": (0, 0, 255), # 蓝色
"cyan": (0, 255, 255), # 青色
"magenta": (228, 0, 127), # 品红色
"yellow": (255, 150, 0), # 黄色
}
a = 0
cp.detect_taps = 1
cp.pixels.brightness = 0.05
# 设置像素的亮度为0.05
pixel_count = 10 # 定义像素数量为10
def scale_range(value):
return round(value / 320 * 9)
# 定义一个颜色轮函数,根据输入位置返回对应颜色的RGB值
def color_wheel(position):
# 如果位置不在0到255范围内,返回黑色
if (position < 0) or (position > 255):
return color_mapping["black"]
# 根据位置计算颜色值并返回RGB元组
if position < 85:
return (int(255 - position * 3), int(position * 3), 0) # 红-绿渐变
elif position < 170:
position -= 85
return (0, int(255 - (position * 3)), int(position * 3)) # 绿-青渐变
else:
position -= 170
return (int(position * 3), 0, int(255 - position * 3)) # 青-蓝渐变
current_pixel = 0 # 初始化当前像素为0
# 无限循环,用于不断更新LED灯
while True:
#检查敲击状态
if cp.tapped:
cp.red_led = 1
print("Tapped!")
a=a+0.01
# 检查开关状态
if cp.switch:
current_pixel += 1 # 开关开启,当前像素增加1
if current_pixel > pixel_count - 1: # 如果当前像素超出范围,重置为0
current_pixel = 0
else:
current_pixel -= 1 # 开关关闭,当前像素减少1
if current_pixel < 0: # 如果当前像素小于0,重置为最大值
current_pixel = pixel_count - 1
if cp.button_b:
print("lingh+!")
cp.pixels.brightness = cp.pixels.brightness +0.01
if cp.button_a:
cp.pixels.brightness = cp.pixels.brightness -0.01
print("lingh-!")
time.sleep(a)
cp.red_led = 0
print(cp.light)
for index in range(pixel_count): # 遍历每个像素
# 计算当前像素的虹彩颜色
rainbow_color = color_wheel(255 // pixel_count * ((current_pixel + index) % pixel_count))
# 设置当前像素的颜色,使用tuple生成RGB值
cp.pixels[index] = tuple(
int(c * ((pixel_count - (current_pixel + index) % pixel_count)) / pixel_count) for c in rainbow_color
)
如视频中展示按下a按键增加亮度 按下b按键减小亮度中间拨码开关可以控制RGB轮换方向,敲击板子使能加速度传感器会让旋转速度变慢
|