STM32——高级定时器的应用
扫描二维码
随时随地手机看文章
/定时器1的配置 输出两路PWM信号 PA8 PA11,计数时钟为400KHZ 计数溢出大小为40000 /
void Tim1Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_OCInitTypeDef TIM_OCInitStruct;
u16 LeftMotor_CCR;
u16 RightMotor_CCR;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1|RCC_APB2Periph_GPIOA|RCC_APB2Periph_AFIO, ENABLE);
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_11 ; // 定时器1 通道1和4
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStruct);
LeftMotor_CCR = RightMotor_CCR = 2000;
//在APB2设置为72MHZ的基础上,对定时器1进行配置
TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0; // 重复计数器无效 */
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up; // 向上计数 */
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1; // 时钟分频 */
TIM_TimeBaseInitStruct.TIM_Prescaler = 180-1; // 预分频系数为180-1,计数器时钟为72MHz/180 = 400KHz */
TIM_TimeBaseInitStruct.TIM_Period = 40000-1;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseInitStruct);
TIM_OCInitStruct.TIM_OutputNState = TIM_OutputNState_Disable;
TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM2;
TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_Low;
TIM_OCInitStruct.TIM_Pulse = LeftMotor_CCR;
TIM_OC1Init(TIM1, &TIM_OCInitStruct);
TIM_OCInitStruct.TIM_Pulse = RightMotor_CCR;
TIM_OC4Init(TIM1, &TIM_OCInitStruct);
TIM_Cmd(TIM1, ENABLE);
TIM_CtrlPWMOutputs(TIM1, ENABLE);
}