Wiznet makers

ruilixin6

Published August 05, 2026 ©

94 UCC

0 VAR

0 Contests

0 Followers

0 Following

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.

COMPONENTS
PROJECT DESCRIPTION

【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

An RGB LED (Red, Green, Blue Light-Emitting Diode) is a light-emitting device composed of a combination of three LEDs in red, green and blue colors; by adjusting the brightness of these three colors, it can generate light of various colors. RGB LEDs are widely used in scenarios such as display screens, decorative lighting and indicator lights.
An RGB LED typically integrates three independent LED chips, each responsible for emitting red, green or blue light respectively. These chips can be controlled independently, so a wide range of colors can be mixed by combining different brightness levels:
The electrical parameters of R6GHBHW RGB LED, where the VF forward voltage of each Light Emitting Diode is different
Red (R): Emits red light, and typically operates at a relatively low voltage
Green (G): Emits green light with a medium operating voltage
Blue (B): Emits blue light and typically operates at a relatively high voltage.
RGB LEDs can produce different colors by mixing red, green, and blue light. We can use Pulse Width Modulation (PWM) to precisely control the brightness of each LED, and the brightness of each color can be adjusted by changing the voltage duty cycle (0~100%), thus realizing rich color variations.
RGB LEDs can be divided into the following two types according to their structure:
Common cathode: The cathodes of all LEDs are connected together, and their anodes are respectively connected to different control terminals of the circuit
Common Anode: The anodes of all LEDs are connected together, while their cathodes are respectively connected to different control terminals of the circuit
The parameters of an RGB LED reflect its electrical and optical properties, which not only determine the luminous efficacy, color and brightness of the LED but also affect its application in circuits:
Forward Voltage (VF): Forward voltage refers to the voltage difference between the two electrodes when an LED is forward conducting; LEDs of different colors have different operating voltage ranges due to variations in their constituent materials.
Maximum Forward Current (IF): Maximum forward current refers to the maximum current allowed to pass through an LED during normal operation, with a common value of 20mA; a current higher than this may damage the LED, cause overheating or reduce the service life of the LED
Luminous Intensity (Iv): Luminous intensity is usually expressed in millicandela (mcd), which describes the brightness of the light emitted by an LED. The luminous intensity depends on the magnitude of the current: the higher the current, the higher the luminous intensity of the LED.
Wavelength: The wavelength of an LED determines the color of the light it emits, and the wavelength range of an RGB LED represents its color; the difference in wavelength is determined by the material of the LED, and photons of different wavelengths have different energies, so LEDs of different colors require different operating voltages.
Reverse Current (IR): Reverse current refers to the current flowing through an LED when it is reverse-biased. Generally, the reverse current of an LED is extremely small, with a typical value on the order of microamps (e. g., 10μA); if the reverse current is excessively high, it may cause damage to the LED.
Taking the electrical parameters of the R6GHBHW-A01 RGB LED as an example, they are shown in the following figure:
Here, we need to add current-limiting resistors to the RGB LED diodes to ensure that the LEDs will not be damaged due to excessive current. The calculation formula for the current-limiting resistor is as follows:
$$R = \frac{V_{in} - V_F}{I_F} $$
The meanings of the respective parameters are as follows:
Vin: Power supply voltage, typically the power supply voltage for LED circuits
VF: Forward Voltage of an LED. The VF value varies for LEDs of different colors.
IF: Operating current of the LED, which is typically 20mA (i. e. 0.02A)

2. PWM Signal Control of RGB LED

Here, we need to insert the 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:
The pin connections are shown in the following table:
All the code for the following experiments is open-source and can be found in the material package we provide under the elegance-devkit v1\Demo\27 PWM_RGBLED folder.
In the following code, we use the 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)
Here, we first define a global dictionary that stores the RGB values of common colors, with each color corresponding to an RGB tuple; for example, red is (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).
Next, we defined an RGB LED control class to encapsulate the control logic of the RGB LED. In the initialization method, we pass the numbers of the red, green and blue pins connected to the RGB LED, initialize these pins to the PWM output mode respectively, set the PWM frequency to 1000Hz, and define two methods:
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 LED
set_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 () method
After flashing the code, you can see the on-board RGB LED cycle through and emit lights of different colors.
 
Documents
Comments Write