【RISC-V MCU CH32V103测评】PWM调节LED灯
[复制链接]
使用定时器及相应的输出功能可实现LED灯的亮度调节,以定时器1的的通道1为例(PA8),它可以通过占空比的控制来得到PWM控制的作用。
也就是说我们可以将LED1与PA8的引脚连接起来,在程序下载后来构成PWM调节的这场戏了,其效果下图所示。
PWM调节效果
其相关程序如下:
#include "debug.h"
#define PWM_MODE1 0
#define PWM_MODE2 1
#define PWM_MODE PWM_MODE2
void TIM1_PWMOut_Init( u16 arr, u16 psc, u16 ccp )
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
RCC_APB2PeriphClockCmd( RCC_APB2Periph_GPIOA | RCC_APB2Periph_TIM1, ENABLE );
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init( GPIOA, &GPIO_InitStructure );
TIM_TimeBaseInitStructure.TIM_Period = arr;
TIM_TimeBaseInitStructure.TIM_Prescaler = psc;
TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit( TIM1, &TIM_TimeBaseInitStructure);
#if (PWM_MODE == PWM_MODE1)
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
#elif (PWM_MODE == PWM_MODE2)
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2;
#endif
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = ccp;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init( TIM1, &TIM_OCInitStructure );
TIM_CtrlPWMOutputs(TIM1, ENABLE );
TIM_OC1PreloadConfig( TIM1, TIM_OCPreload_Disable );
TIM_ARRPreloadConfig( TIM1, ENABLE );
TIM_Cmd( TIM1, ENABLE );
}
int main(void)
{
USART_Printf_Init(115200);
printf("SystemClk:%d\r\n",SystemCoreClock);
TIM1_PWMOut_Init( 100, 48000-1, 50 );
while(1);
}
此外,我们还可以采用动态调整占空比的方法来实现呼吸灯的显示效果,其思路是将pwmval设置为PWM的比较值,令其在0~300间变化。当pwmval逐渐增大时,LED的亮度加强;反之当pwmval逐渐减小时,LED的亮度变暗。另外,为了便于观察可添加延时函数来减慢亮度变化的速度。
int main(void)
{
u16 pwmval=0;
u8 a=1;
Delay_Init();
USART_Printf_Init(115200);
printf("SystemClk:%d\r\n",SystemCoreClock);
TIM1_PWMOut_Init( 899, 0, 500 );
while(1)
{
Delay_Ms(10);
if(a) pwmval++;
else pwmval--;
if(pwmval >300) a =0;
if(pwmval==0) a =1;
TIM_SetCompare1(TIM1, pwmval);
}
}
另外,你知道如何将PA8的输出口移到PA9和PA10上吗?
下次再做详细的介绍,感兴趣的话可以继续关注呦!
|