第十一届蓝桥杯嵌入式组别底层驱动程序11(PWM①)
PWM输出模式
PWM的训练目标在于
①输出两路占空比可调,频率可调的PWM
②捕获两路PWM的频率和占空比
以下:输出两路频率固定占空比可调的PWM
要根据不同的题目需求来选择不同方式来捕获PWM或者输出PWM
引脚 对应时钟通道 扩展版说明
PA1 TIM2_CH2 可以调节输入PWM的频率
PA2 TIM2_CH3 可以调节输入PWM的频率
PA6 TIM3_CH1 可以调节输入PWM的占空比
PA7 TIM3_CH2 可以调节输入PWM的占空比
首先先用PA1,PA2输出两路频率固定的PWM波占空比
通过TIM_SetCompare2()和TIM_SetCompare3()来改变两个通道输出PWM的占空比
PA1输出占空比为30%
PA2输出占空比为50%
void PWM_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_1 | GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
TIM_TimeBaseStructure.TIM_Period = 999;//TIM2的预装载值为999
TIM_TimeBaseStructure.TIM_Prescaler = 71;//分频系数为71//72Mhz/(72*1000)=1Khz
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;//直接设置了TIM2的CH2和CH3为PWM输出模式1,以及输出极性为高
TIM_OC2Init(TIM2, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Enable);
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OC3Init(TIM2, &TIM_OCInitStructure);
TIM_OC3PreloadConfig(TIM2, TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM2, ENABLE);
TIM_Cmd(TIM2, ENABLE);
}
#ifndef __PWM_H__
#define __PWM_H__
void PWM_Init(void);
#endif
uint16_t PA1=300,PA2=500;//PA2输出占空比为50%
PWM_Init();
TIM_SetCompare2(TIM2, PA1);//PA1输出占空比为10%
TIM_SetCompare3(TIM2, PA2);//PA2输出占空比为20%
可以通过按键触发中断,将PA1输出的占空比进行更改
void EXTI0_IRQHandler(void)
{
if(EXTI_GetITStatus(EXTI_Line0) != RESET)
{
EXTI_ClearITPendingBit(EXTI_Line0);
if(PA1 < 1000)
{
PA1 += 100;
TIM_SetCompare2(TIM2, PA1);//PA1输出占空比为10%
}
}
}