blog:micropython驱动esp32-s3上的rgb-led灯_ws2812
Micropython驱动ESP32-S3上的RGB-LED灯(WS2812)
MicroPython 的 neopixel 库是一个用来控制 NeoPixel LED(基于 WS2812 或类似协议的 RGB LED)的模块。它提供了一种简单的方法来管理这些 LED 的颜色和亮度。
记录一下成功测试的代码:
import machine import neopixel import time # 配置 RGB LED PIN = 48 # GPIO38 NUM_LEDS = 8 # LED 灯珠的数量,根据实际情况调整 LED_COUNT = 8 # 初始化 Neopixel np = neopixel.NeoPixel(machine.Pin(PIN), NUM_LEDS) def set_color(index, r, g, b, brightness=1.0): """ 设置指定 LED 的颜色 :param index: LED 的索引(从 0 开始) :param r: 红色值(0-255) :param g: 绿色值(0-255) :param b: 蓝色值(0-255) :param brightness: 亮度调整系数(0.0-1.0) """ r = int(r * brightness) g = int(g * brightness) b = int(b * brightness) np[index] = (g, r, b) # Neopixel 是 GRB 排序 np.write() # 将数据写入 LED def rainbow_cycle(delay_ms=50): """ 循环显示彩虹效果 :param delay_ms: 每次循环的延迟时间(毫秒) """ for j in range(256): # 循环 256 次 for i in range(NUM_LEDS): # 每个 LED 单独计算颜色 pixel_index = (i * 256 // NUM_LEDS) + j np[i] = wheel(pixel_index & 255) np.write() machine.sleep(delay_ms) def wheel(pos): """ 生成彩虹颜色 :param pos: 位置(0-255) :return: (g, r, b) 格式的颜色元组 """ if pos < 85: return (pos * 3, 255 - pos * 3, 0) elif pos < 170: pos -= 85 return (255 - pos * 3, 0, pos * 3) else: pos -= 170 return (0, pos * 3, 255 - pos * 3) def set_all_red(): """ 将所有 LED 设置为红色。 """ for i in range(LED_COUNT): np[i] = (255, 0, 0) # 红色 (R, G, B) np.write() # 更新 LED 显示 def set_all_white(): """ 将所有 LED 设置为白色。 """ for i in range(LED_COUNT): np[i] = (255, 255, 255) # 白色 (R, G, B) np.write() # 更新 LED 显示 def turn_off_all_leds(): """ 关闭所有 LED。 """ for i in range(LED_COUNT): np[i] = (0, 0, 0) # 设置每颗 LED 的 RGB 值为 (0, 0, 0) np.write() # 更新 LED 显示 # 测试代码 #set_color(0, 255, 0, 0) # 第一个 LED 显示红色 #time.sleep(2) #set_color(1, 0, 255, 0) # 第二个 LED 显示绿色 #time.sleep(2) #set_color(2, 0, 0, 255) # 第三个 LED 显示蓝色 #time.sleep(2) set_all_red() time.sleep(2) set_all_white() time.sleep(2) turn_off_all_leds() #rainbow_cycle() # 显示彩虹效果
blog/micropython驱动esp32-s3上的rgb-led灯_ws2812.txt · 最后更改: 2024/12/24 12:03 由 owl