【AB32VG1开发板测评】PWM调节及呼吸灯
[复制链接]
本帖最后由 jinglixixi 于 2021-9-13 17:09 编辑
AB32VG1内部配有6个PWM输出通道,若以PWM来控制RGB_LED就可产生呼吸灯效果,该RGB_LED的引脚连接如图1所示。
图1 RGB_LED连接端口
实现呼吸灯效果的步骤如下:
1. 创建一个基于AB32VG1开发板的RT-Thread新项目;
2. 在左侧资源管理器中点击“RT-Thread Setting”,然后选取“更多配置”;
3. 选取“硬件”选项卡,按图2所示进行设置,由此可知PWM2所控制的是LED_R;
图2 功能配置
4. 按“Ctrl + S”进行保存,以使RT Thread的配置生效;
5. 在左侧资源管理器的application下,新建一个文件pwm.c,其内容为:
#include <rtthread.h>
#include "board.h"
#define PWM_DEV_NAME "t5pwm" /* PWM设备名称 */
#define PWM_DEV_CHANNEL 1 /* PWM通道 */
struct rt_device_pwm *pwm_dev; /* PWM设备句柄 */
ALIGN(RT_ALIGN_SIZE)
static uint8_t PWM_Thread_Stack[1024];
static void PWM_Thread_Entry(void *para);
static struct rt_thread pwm_thread;
rt_uint32_t period, pulse;
void Pwm_Init(void){
period = 1000000; /* 周期 = 1M/period kHz */
pulse = 0; /* PWM脉冲宽度值(0 - period) */
pwm_dev = (struct rt_device_pwm *)rt_device_find(PWM_DEV_NAME);
RT_ASSERT(pwm_dev != RT_NULL);
/* 设置PWM周期和脉冲宽度 */
rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, pulse);
/* 使能设备 */
rt_pwm_enable(pwm_dev, PWM_DEV_CHANNEL);
}
static void PWM_Thread_Entry(void *para){
Pwm_Init();
while(1){
/*使RGB灯红灯闪烁*/
for (int var = 0; var < period; var += 10000) {
rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, var);
rt_thread_mdelay(1000);
}
}
}
int Pwm_Thread_Init(void){
rt_thread_init(&pwm_thread, "pwm_thread", PWM_Thread_Entry, RT_NULL,
&PWM_Thread_Stack[0], sizeof(PWM_Thread_Stack), 10, 10);
rt_thread_startup(&pwm_thread);
return 0;
}
INIT_APP_EXPORT(Pwm_Thread_Init);
static void PWM_Thread_Entry(void *para){
Pwm_Init();
while(1){
/*使RGB灯红灯闪烁*/
for (int var = 0; var < period; var += 10000) {
rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, var);
rt_thread_mdelay(10);
}
for (int var = period; var >0; var -= 10000) {
rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, var);
rt_thread_mdelay(10);
}
}
}
6. 对程序进行编译和下载,其测试结果如图3所示。该呼吸灯的特点是延时时间适中,呈现的调节效果为三角波,即渐变增强亮度再渐变减弱亮度。
图3显示效果
|