定时器的输出比较功能应用最广泛的就是PWM(脉冲宽度调制),我们可以通过定时器的输出比较功能,直接从单片机引脚上输出硬件PWM方波。本次以呼吸灯为例,带大家领略PWM的美感。
1.PWM初始化
将PA0配置为定时器的输出比较引脚,输出PWM方波,因此我们需要在PA0引脚接一个限流电阻与放光二极管,方便观察实验现象。
void PWM_Init(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStruct;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStruct);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_InternalClockConfig(TIM2);
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStruct.TIM_Period = 100 - 1;
TIM_TimeBaseInitStruct.TIM_Prescaler = 720 - 1;
TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStruct);
TIM_OCInitTypeDef TIM_OCInitStruct;
TIM_OCStructInit(&TIM_OCInitStruct); //给结构体赋初始值,确保在一个确定的状态
TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_Pulse = 50;
TIM_OC1Init(TIM2, &TIM_OCInitStruct);
TIM_Cmd(TIM2, ENABLE);
}
2.使用
使用库函数TIM_SetCompare1()
来动态调整PWM的占空比,从而实现呼吸灯的效果
/*呼吸灯*/
int main(void)
{
uint8_t i;
while(1)
{
for(i = 0; i <100; i++)
{
TIM_SetCompare1(TIM2, i);
Delay_ms(10);
}
for(i = 0; i <100; i++)
{
TIM_SetCompare1(TIM2, 100 - i);
Delay_ms(10);
}
}
}
本次笔记基于B站UP主江协科技STM32教程总结而来