GD32 STM32 pwm 调RGB三色灯
在 GD32/STM32上通过 PWM 调节 RGB 三色灯的亮度是一个常见的应用。你可以使用 GD32F470 的定时器模块来生成 PWM 信号,然后将这些信号输出到 RGB 三色灯的红、绿、蓝三条控制线上,以调节它们的亮度。以下是实现的基本步骤:
1. 配置 GPIO
首先,配置 GPIO 引脚,使其能够输出 PWM 信号。假设你将 RGB 灯的红、绿、蓝三色分别连接到定时器的不同通道上。
// 假设使用 GPIOA 端口,定时器使用 TIM1,通道分别为 CH1、CH2、CH3
gpio_init(GPIOA, GPIO_MODE_AF_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10);
// 将 GPIO 引脚设置为定时器的复用功能
gpio_pin_af_config(GPIOA, GPIO_AF_1, GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10);
2. 配置定时器
接下来,配置定时器来生成 PWM 信号。我们可以使用 TIM1 作为例子。
timer_parameter_struct timer_initpara;
timer_oc_parameter_struct timer_ocintpara;
timer_deinit(TIMER1);
timer_initpara.prescaler = 108 - 1; // 设置预分频器
timer_initpara.alignedmode = TIMER_COUNTER_EDGE;
timer_initpara.counterdirection = TIMER_COUNTER_UP;
timer_initpara.period = 999; // 设置周期值
timer_initpara.clockdivision = TIMER_CKDIV_DIV1;
timer_init(TIMER1, &timer_initpara);
// 配置 PWM 输出模式
timer_ocintpara.outputstate = TIMER_CCX_ENABLE;
timer_ocintpara.outputnstate = TIMER_CCXN_DISABLE;
timer_ocintpara.ocpolarity = TIMER_OC_POLARITY_HIGH;
timer_ocintpara.ocidlestate = TIMER_OC_IDLE_STATE_LOW;
timer_channel_output_config(TIMER1, TIMER_CH_1, &timer_ocintpara);
timer_channel_output_config(TIMER1, TIMER_CH_2, &timer_ocintpara);
timer_channel_output_config(TIMER1, TIMER_CH_3, &timer_ocintpara);
// 设置 PWM 模式及占空比
timer_channel_output_pulse_value_config(TIMER1, TIMER_CH_1, 0); // 红色通道初始值
timer_channel_output_mode_config(TIMER1, TIMER_CH_1, TIMER_OC_MODE_PWM0);
timer_channel_output_shadow_config(TIMER1, TIMER_CH_1, TIMER_OC_SHADOW_DISABLE);
timer_channel_output_pulse_value_config(TIMER1, TIMER_CH_2, 0); // 绿色通道初始值
timer_channel_output_mode_config(TIMER1, TIMER_CH_2, TIMER_OC_MODE_PWM0);
timer_channel_output_shadow_config(TIMER1, TIMER_CH_2, TIMER_OC_SHADOW_DISABLE);
timer_channel_output_pulse_value_config(TIMER1, TIMER_CH_3, 0); // 蓝色通道初始值
timer_channel_output_mode_config(TIMER1, TIMER_CH_3, TIMER_OC_MODE_PWM0);
timer_channel_output_shadow_config(TIMER1, TIMER_CH_3, TIMER_OC_SHADOW_DISABLE);
// 启动定时器
timer_enable(TIMER1);
3. 调整颜色
通过改变各通道的占空比,你可以控制 RGB 灯的颜色和亮度。例如,要设置红色:
void set_rgb(uint16_t red, uint16_t green, uint16_t blue) {
timer_channel_output_pulse_value_config(TIMER1, TIMER_CH_1, red); // 红色
timer_channel_output_pulse_value_config(TIMER1, TIMER_CH_2, green); // 绿色
timer_channel_output_pulse_value_config(TIMER1, TIMER_CH_3, blue); // 蓝色
}
4. 示例
例如,要设置 RGB 灯为橙色(红色高、绿色中、蓝色低):
set_rgb(800, 400, 0);
总结
通过以上步骤,你就可以在 GD32F470 上使用 PWM 控制 RGB 三色灯的颜色和亮度了。你可以根据需要调整各个通道的占空比来实现不同的颜色组合。
作者:wsdtr