void TIM2_PWM_Init(void)
{
//定义结构体
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_InitStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
//挂接时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2,ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); //使能GPIO外设和AFIO复用功能模块时钟使能
//配置引脚
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
//定时器基础配置
TIM_InitStructure.TIM_ClockDivision = 0; //设置时钟分割:TDTS = Tck_tim
TIM_InitStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIM向上计数模式
TIM_InitStructure.TIM_Period = 9999; //自动重装值
TIM_InitStructure.TIM_Prescaler = 71; //时钟预分频数
TIM_TimeBaseInit(TIM2,&TIM_InitStructure);
//PWM配置
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //选择定时器模式:TIM脉冲宽度调制模式1
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //比较输出使能
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性:TIM输出比较极性高
TIM_OC4Init(TIM2,&TIM_OCInitStructure);
TIM_OC4PreloadConfig(TIM2,TIM_OCPreload_Enable); //使能TIMx在CCR2上的预装载寄存器
TIM_ARRPreloadConfig(TIM2, ENABLE); //使能TIMx在ARR上的预装载寄存器
TIM_Cmd(TIM2, ENABLE); //使能TIMx外设
}
int main(void)
{
TIM2_PWM_Init();
TIM_SetCompare4(TIM2,4999); //设置占空比为50%
while(1);
}
STM32定时器计算公式:
72000000/((TIM_Period+1)*(TIM_Prescaler+1)) = f
T = 1/f
f:定时器频率单位(Hz)
T:定时器周期单位(S)
代入上述配置的参数可得:
72000000/((9999+1)*(71+1)) = 100(Hz)
T = 1/100 = 0.01(S)
上述配置了TIM2 CH4的PWM,周期是10Ms
main函数中的TIM_SetCompare4(TIM2,4999);函数设置PWM占空比。
配置如下:
TIM_SetCompare4(TIMx,(TIM_Period*i%));
来源:CSDN
作者:zhai17863966493
链接:https://blog.csdn.net/zhai17863966493/article/details/104142290