为了展示PWM效果,这里用ADC来采集PWM输出通道的电平变化
-
第一步,进入RT-Thread Settings配置PWM驱动
-
第二步,进入board.h,打开PWM宏
-
第三步,进入STM32CubeMX,配置时钟及PWM
-
第四步,回到RT-Thread Studio,编译发现程序报错
-
第五步,双击错误定位到具体位置,屏蔽相关错误,再次编译,发现错误消失
-
第六步,添加构建CubeMX生成的tim.c
-
第七步,进入main.c,查找PWM设备,设置PWM周期和脉冲宽度,并使能PWM
struct rt_device_pwm *pwm_dev=(struct rt_device_pwm *)rt_device_find(“PWM3”);rt_pwm_set(pwm_dev, 3, period, pulse); /* 周期为period、脉宽为pulse */
rt_pwm_enable(pwm_dev, 3); /* 使能通道3 */
- 第八步,设置脉宽变化,方便ADC采样查看
if (dir){pulse += 500; /* 从0值开始每次增加5000ns */}else{pulse -= 500; /* 从最大值开始每次减少5000ns */}if (pulse >= period){dir = 0;}if (0 == pulse){dir = 1;} rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, pulse);
第九步,ADC采样
value = rt_adc_read(adc_dev, ADC_DEV_CHANNEL); /* 读取采样值 */
vol = value * REFER_VOLTAGE / CONVERT_BITS; /* 转换为对应电压值 */
rt_kprintf("%d --- %d.%02d \n", value,vol / 100, vol % 100);
综上,main.c
#include <rtthread.h>
#include <rtdbg.h>
#include <rtdevice.h>
#include <board.h>#define DBG_TAG "main"
#define DBG_LVL DBG_LOG#define ADC_DEV_NAME "adc1" /* ADC 设备名称 */
#define ADC_DEV_CHANNEL 1 /* ADC 通道 */
#define REFER_VOLTAGE 330 /* 参考电压 3.3V,数据精度乘以100保留2位小数*/
#define CONVERT_BITS (1 << 12) /* 转换位数为12位 */#define PWM_DEV_NAME "pwm3" /* PWM设备名称 */
#define PWM_DEV_CHANNEL 3 /* PWM通道 PB1 */
struct rt_device_pwm *pwm_dev; /* PWM设备句柄 */int main(void)
{/*ADC*/rt_adc_device_t adc_dev;rt_uint32_t value, vol;/*PWM*/rt_uint32_t period, pulse, dir;period = 500000; /* 周期为0.5ms,单位为纳秒ns */dir = 1; /* PWM脉冲宽度值的增减方向 */pulse = 0; /* PWM脉冲宽度值,单位为纳秒ns */adc_dev = (rt_adc_device_t)rt_device_find(ADC_DEV_NAME); /* 查找设备 */if (adc_dev == RT_NULL){rt_kprintf("adc sample run failed! can't find %s device!\n", ADC_DEV_NAME);return RT_ERROR;}else {rt_kprintf("find %s success!\n",ADC_DEV_NAME);}rt_adc_enable(adc_dev, ADC_DEV_CHANNEL);/* 查找设备 */pwm_dev = (struct rt_device_pwm *)rt_device_find(PWM_DEV_NAME);if (pwm_dev == RT_NULL){rt_kprintf("pwm sample run failed! can't find %s device!\n", PWM_DEV_NAME);return RT_ERROR;}/* 设置PWM周期和脉冲宽度默认值 */rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, pulse);/* 使能设备 */rt_pwm_enable(pwm_dev, PWM_DEV_CHANNEL);while (1){rt_thread_mdelay(100);if (dir){pulse += 500; /* 从0值开始每次增加5000ns */}else{pulse -= 500; /* 从最大值开始每次减少5000ns */}if (pulse >= period){dir = 0;}if (0 == pulse){dir = 1;}/* 设置PWM周期和脉冲宽度 */rt_pwm_set(pwm_dev, PWM_DEV_CHANNEL, period, pulse);/* 读取采样值 */value = rt_adc_read(adc_dev, ADC_DEV_CHANNEL);/* 转换为对应电压值 */vol = value * REFER_VOLTAGE / CONVERT_BITS;rt_kprintf("%d --- %d.%02d \n", value,vol / 100, vol % 100);}return RT_EOK;
}
实测如下: