当前位置: 资讯 >

热议:PWM驱动LED实现呼吸灯效果

来源:华仔stm32 发表日期:2023-04-24 15:18:35

目的

利用pwm实现呼吸为灯效果


(资料图)

实验环境

TBK-RD8T3x开发板

实现原理

RD8T37单片机最多提供 14 路 PWM,这 14路 PWM 分为两类:多功能 PWM:共8路,只有一组,即 PWM0,输出信号口为: PWM0 0~07。

我们只需要修改PWM0的占空比就可以实现LED灯的亮度。

实现步骤

1、在keil工程加入rd8_pwm.c

2、根据数据手册与原理图,我这里选用P42为PWM输出:

3、初始化PWM0通道5

/******************************************************函数名称: SC_PWM0_Init*函数功能: PWM0初始化函数*入口参数:void*出口参数:void *****************************************************/void SC_PWM0_Init(void){/*PWM0独立模式*/PWM_Init(PWM0_PRESSEL_FHRC_D1,255);/*PWM00 独立模式*/PWM_IndependentModeConfigEX(PWM05,0, PWM_OUTPUTSTATE_ENABLE);/*PWM0*/PWM_Aligned_Mode_Select(PWM0_Edge_Aligned_Mode);/*PWM0*/PWM_FaultDetectionConfigEX(PWM0_Type,DISABLE);/*PWM0*/PWM_FaultDetectionModeConfigEX(PWM0_Type,PWM0_Immediate_Mode,PWM0_FaultDetectionVoltage_Low,PWM0_WaveFilteringTime_0us);/*PWM0中断使能*/PWM_ITConfigEX(PWM0_Type,DISABLE,LOW);/*PWM0开关*/PWM_CmdEX(PWM0_Type,ENABLE);/*PWM0_Init write here*/}

4、动态修改占空比的函数为:

PWM_IndependentModeConfig(PWM05,pwm_num);

5、为了达到非阻塞式的动态修改占空比,以达到实现呼吸灯的效果,我附了main.c的代码如下:

#include "rd8.h"#include "rd8_pwm.h"uint8_t sta;uint32_t count = 0;void LED_Init(void){P3CON |= 0x1E; //P3 0b0001 1110 输出P4CON |= 0x0F; //P4 0b0000 1111}void Timer0Iint(void){TMOD |= 0x01;  // 配置定时器0为 16位定时器,  TH0、TL0全用 TH0 =(65536-1000)/256;   //1000us定时,即1毫秒溢出产生中断TL0 =(65536-1000)%256;  //1000us定时,即1毫秒溢出产生中断ET0 = 1;//开启定时器0中断EA = 1;//开启全局中断TR0 = 1;//定时器0开始计数;}/******************************************************函数名称: SC_PWM0_Init*函数功能: PWM0初始化函数*入口参数:void*出口参数:void *****************************************************/void SC_PWM0_Init(void){/*PWM0独立模式*/PWM_Init(PWM0_PRESSEL_FHRC_D1,255);/*PWM00 独立模式*/PWM_IndependentModeConfigEX(PWM05,0, PWM_OUTPUTSTATE_ENABLE);/*PWM0*/PWM_Aligned_Mode_Select(PWM0_Edge_Aligned_Mode);/*PWM0*/PWM_FaultDetectionConfigEX(PWM0_Type,DISABLE);/*PWM0*/PWM_FaultDetectionModeConfigEX(PWM0_Type,PWM0_Immediate_Mode,PWM0_FaultDetectionVoltage_Low,PWM0_WaveFilteringTime_0us);/*PWM0中断使能*/PWM_ITConfigEX(PWM0_Type,DISABLE,LOW);/*PWM0开关*/PWM_CmdEX(PWM0_Type,ENABLE);/*PWM0_Init write here*/}void main(void){//LED_Init();uint8_t pwm_num;uint8_t f;SC_PWM0_Init();Timer0Iint();f=0;pwm_num = 0;while(1){if(sta ==1){sta = 0;if(f ==0){pwm_num++;PWM_IndependentModeConfig(PWM05,pwm_num);}else if (f ==1){pwm_num--;PWM_IndependentModeConfig(PWM05,pwm_num);}if(pwm_num == 255){f = 1;}else if(pwm_num == 0){f = 0;}}}}void Timer0() interrupt 1{//每次产生中断后初始化定时器初值, 1ms秒产生1次中断TH0=(65536-1000)/256;TL0=(65536-1000)%256;count ++;if(count == 10){sta =1;count = 0;}}

实现效果

审核编辑 黄宇

x
推荐阅读 更多