Basics: RGB LED Hardware Principles and Raspberry Pi Pico PWM Control Practice
MicroPython PWM‑based RGB‑LED driver class, supporting RGB‑value mapping and named‑color switching for multi‑color lighting effects.
【Preliminary Note】The original hardware example in this article was written based on the RP2040. The actual hardware used in this hands-on demonstration features the W55RP20 as the main controller chip. The circuit logic and UF2 flashing operation principles are universally applicable, with only the main controller model differing. The original chip model mentioned in the circuit descriptions below is provided for reference purposes only.
PWM Signal Controls RGB LED
1. Basics of RGB LEDs
2. PWM Signal Control of RGB LED
Fengya No. 1 Board - Environment and Storage Acquisition Board into the Fengya No. 1 Board - Universal Compatible Expansion Board, and meanwhile turn on the PWM_B, PWM_G and PWM_R options of the SWITCH2 DIP switch on the Fengya No. 1 Board - Environment and Storage Acquisition Board. The physical connection diagram is shown as follows:under the elegance-devkit v1\Demo\27 PWM_RGBLED folder.PWM module to control the GPIO pins of the Raspberry Pi Pico to output PWM signals, thereby driving the RGB LED. The sample code is as follows:# Python env : MicroPython v1.23.0
# -*- coding: utf-8 -*-
# @Time : 2024/9/20 下午3:18
# @Author : 李清水
# @File : main.py
# @Description : PWM类使用,驱动RGB LED产生不同颜色的光
# ======================================== 导入相关模块 =========================================
# 导入硬件相关的模块
from machine import Pin, PWM
# 导入时间相关模块
import time
# ======================================== 全局变量 ============================================
# 定义颜色RGB值到PWM占空比的映射表(常见颜色)
COLOR_PWM_VALUES = {
'red': (255, 0, 0), # 红色
'green': (0, 255, 0), # 绿色
'blue': (0, 0, 255), # 蓝色
'yellow': (255, 255, 0), # 黄色
'cyan': (0, 255, 255), # 青色
'magenta': (255, 0, 255), # 品红
'white': (255, 255, 255), # 白色
'black': (0, 0, 0), # 关闭LED
}
# ======================================== 功能函数 ============================================
# 将8位值(0-255)转换为16位PWM值(0-65535)
def map_to_pwm(value: int) -> int:
"""
将8位颜色值(0-255)映射到16位PWM占空比(0-65535)。
Args:
value (int): 0-255之间的颜色值。
Returns:
int: 映射到0-65535范围内的PWM占空比。
"""
return int(value * 65535 / 255)
# ======================================== 自定义类 ============================================
# RGB LED控制类
class RGBLed:
"""
RGB LED控制类,用于通过PWM驱动RGB LED产生不同颜色的光。
该类封装了对RGB LED的控制逻辑,支持通过PWM调节红、绿、蓝三个通道的亮度,
从而实现多种颜色的显示。此外,支持通过颜色名直接设置LED的颜色。
Attributes:
red_pwm (PWM): 红色LED的PWM实例。
green_pwm (PWM): 绿色LED的PWM实例。
blue_pwm (PWM): 蓝色LED的PWM实例。
Methods:
__init__(self, red_pin: int, green_pin: int, blue_pin: int):
初始化RGB LED类实例。
set_color(self, red_val: int, green_val: int, blue_val: int) -> None:
设置RGB LED的颜色。
set_color_by_name(self, color_name: str) -> None:
通过颜色名设置RGB LED的颜色。
"""
def __init__(self, red_pin: int, green_pin: int, blue_pin: int):
"""
初始化RGB LED。
Args:
red_pin (int): 红色LED连接的引脚编号。
green_pin (int): 绿色LED连接的引脚编号。
blue_pin (int): 蓝色LED连接的引脚编号。
"""
# 初始化红、绿、蓝三个PWM通道
self.red_pwm = PWM(Pin(red_pin))
self.green_pwm = PWM(Pin(green_pin))
self.blue_pwm = PWM(Pin(blue_pin))
# 设置PWM频率(典型值为1000Hz)
self.red_pwm.freq(1000)
self.green_pwm.freq(1000)
self.blue_pwm.freq(1000)
def set_color(self, red_val: int, green_val: int, blue_val: int) -> None:
"""
设置RGB LED的颜色。
Args:
red_val (int): 红色RGB值,取值范围为0-255。
green_val (int): 绿色RGB值,取值范围为0-255。
blue_val (int): 蓝色RGB值,取值范围为0-255。
Returns:
None
"""
# 将8位颜色值映射到16位PWM值,并设置占空比
self.red_pwm.duty_u16(map_to_pwm(red_val))
self.green_pwm.duty_u16(map_to_pwm(green_val))
self.blue_pwm.duty_u16(map_to_pwm(blue_val))
def set_color_by_name(self, color_name: str) -> None:
"""
通过颜色名设置RGB LED的颜色。
Args:
color_name (str): 颜色名,比如'red', 'green', 'blue'等。
Returns:
None
"""
# 获取颜色对应的RGB值
# 从字典中获取指定键对应的值,如果找不到指定的键,则返回默认值 (0, 0, 0)
color_values = COLOR_PWM_VALUES.get(color_name.lower(), (0, 0, 0))
# 设置RGB LED的颜色
# 使用了 Python 中的解包操作符,将元组中的三个值分别传递给
# set_color() 方法的三个参数 red_val、green_val 和 blue_val
self.set_color(*color_values)
# ======================================== 初始化配置 ==========================================
# 上电延时3s
time.sleep(3)
# 打印调试信息
print("FreakStudio : Use PWM to drive a RGB LED")
# 初始化RGB LED类:使用红色引脚为2,绿色引脚为3,蓝色引脚为4
rgb_led = RGBLed(red_pin=2, green_pin=3, blue_pin=4)
# ======================================== 主程序 ===========================================
# 设置为一个中等红、绿色最亮、蓝色较暗的颜色
rgb_led.set_color(128, 255, 64)
# 延时3s
time.sleep(3)
# 循环控制RGB LED变换颜色
while True:
# 设置为红色,并延时1s
rgb_led.set_color_by_name('red')
time.sleep(1)
# 设置为绿色,并延时1s
rgb_led.set_color_by_name('green')
time.sleep(1)
# 设置为蓝色,并延时1s
rgb_led.set_color_by_name('blue')
time.sleep(1)
# 设置为黄色,并延时1s
rgb_led.set_color_by_name('yellow')
time.sleep(1)
# 设置为青色,并延时1s
rgb_led.set_color_by_name('cyan')
time.sleep(1)
# 设置为品红,并延时1s
rgb_led.set_color_by_name('magenta')
time.sleep(1)
# 设置为白色,并延时1s
rgb_led.set_color_by_name('white')
time.sleep(1)
# 设置为黑色,并延时1s
rgb_led.set_color_by_name('black')
time.sleep(1) (255,0, 0), and then we define a map_to_pwm function that maps RGB values (in the range of 0-255) to PWM values (in the range of 0-65535).set_color_by_name () method: Sets the color of the RGB LED by color name. It looks up the RGB value corresponding to the color name from the global dictionary COLOR_PWM_VALUES, and returns (0,0, 0) by default if no match is found, which means turning off the LEDset_color () method: Used to set the color of the RGB LED, which accepts three parameters (the duty cycles of red, green and blue, ranging from 0 to 255). It uses map_to_pwm () to map the RGB values to a 16-bit PWM duty cycle, and sets the PWM value of each color channel via the duty_u16 () methodRGB LED cycle through and emit lights of different colors.