STM32高级定时器用于普通定时,定时周期变长
最近在用stm32定时器控制步进电机,由于普通定时器不够用,只能把TIM1当普通定时器用,我随手就把普通定时器的代码搬过去。
void cs_Timer_Init(void) //TIM1 us级 { TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; /* Time base configuration */ TIM_TimeBaseStructure.TIM_Period = 1000; TIM_TimeBaseStructure.TIM_Prescaler = 71; TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure); TIM_ClearITPendingBit(TIM1, TIM_IT_Update); TIM_ITConfig(TIM1, TIM_IT_Update , ENABLE); }
编译下载后,发现步进电机转的很慢,和原先预计的不一样,第一反应是怀疑拷贝过来的代码有问题,核对了一边发现没问题,用逻辑分析仪测试了,发现真是定时器慢了,在检查代码,发现 TIM_TimeBaseInitTypeDef 结构体中的一个参数 TIM_RepetitionCounter 一直没用,查查资料,这个值是计数值满溢出几次才进入中断,就试着把这个值也初始化为0,发现步进电机变快了,测量波形,定时器OK。
void cs_Timer_Init(void) //TIM1 us级 { TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; /* Time base configuration */ TIM_TimeBaseStructure.TIM_Period = 1000; TIM_TimeBaseStructure.TIM_Prescaler = 71; TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseStructure.TIM_RepetitionCounter = 0; //修改此处 TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure); TIM_ClearITPendingBit(TIM1, TIM_IT_Update); TIM_ITConfig(TIM1, TIM_IT_Update , ENABLE); }