定时器的.c文件:
/*****************************************************************************
TIM1,TIM2,TIM3,TIM4,TIM5,TIM8输出4路PWM配置
要用TIM2-TIM5记得注销TIM1,TIM8
要用TIM1,TIM8记得注销TIM2-TIM5
默认:TIM2-TIM5
注意:要使用TIM8的话别忘记把
TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset ;
的注释取消掉,TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset ;
的具体位置在下方。
arr和psc要自己配置(根据自己的需要配置)
公式:
72MHz / ((arr+1)*(psc+1)) =F(HZ)
T=1/F(s)
配置方式:
在主函数加入PWM_Init (999,0);
我的arr和psc的默认值分别是
arr=999,psc=0
*********************************************************************************/
void PWM_Init (u16 arr,u16 psc)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
PWM_motor_Init();
//RCC_APB2PeriphClockCmd(TIMX_CLKCmd2, ENABLE);//TIM1,TIM8
RCC_APB1PeriphClockCmd(TIMX_CLKCmd, ENABLE);//TIM2--TIM5(TIM2,TIM3,TIM4,TIM5)
//PWM端口1
RCC_APB2PeriphClockCmd(TIMX_GPIO_CLK1, ENABLE);
GPIO_InitStructure.GPIO_Pin = TIMX_GPIO_PIN1;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(TIMX_GPIO1, &GPIO_InitStructure);
//PWM端口2
RCC_APB2PeriphClockCmd(TIMX_GPIO_CLK2, ENABLE);
GPIO_InitStructure.GPIO_Pin = TIMX_GPIO_PIN2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(TIMX_GPIO2, &GPIO_InitStructure);
//PWM端口3
RCC_APB2PeriphClockCmd(TIMX_GPIO_CLK3, ENABLE);
GPIO_InitStructure.GPIO_Pin = TIMX_GPIO_PIN3;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(TIMX_GPIO3, &GPIO_InitStructure);
//PWM端口4
RCC_APB2PeriphClockCmd(TIMX_GPIO_CLK4, ENABLE);
GPIO_InitStructure.GPIO_Pin = TIMX_GPIO_PIN4;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(TIMX_GPIO4, &GPIO_InitStructure);
//TIME配置模式
TIM_TimeBaseStructure.TIM_Period = arr;
TIM_TimeBaseStructure.TIM_Prescaler = psc;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIMX, &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;
//TIM_OCInitStructure.TIM_OCIdleState = TIM_OCIdleState_Reset ;//TIM8关闭空闲状态(使用TIM8时候开启)
/*********************************************************************************
|