2016-08-01 11:55 AM
I am working on a project that would benefit from a timer whose speed could be changed in real time within the program. Right now I have a timer set up with Tim_CMD, but the prescaler for that is set when it is initialized.
I would need to be able to scale the timer speed smoothly between different rates. Can anyone recommend a good method for setting this up? #!timer #!stm322016-08-01 12:27 PM
Both the PSC and ARR registers are buffered and used at the next update event, if you change them in the current update interrupt they will change seamlessly at the next one.
2016-08-01 02:43 PM
So would that mean to change one of them I could simply put:
timerInitStructure.TIM_Prescaler = 6000;ortimerInitStructure.TIM_Period = 1;In my while loop?After initializing like so: RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE); TIM_TimeBaseInitTypeDef timerInitStructure; timerInitStructure.TIM_Prescaler = 750; timerInitStructure.TIM_CounterMode = TIM_CounterMode_Up; timerInitStructure.TIM_Period = 1; timerInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; timerInitStructure.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM2, &timerInitStructure); TIM_Cmd(TIM2, ENABLE);That would definitely make things very easy. Let me know if there's anything I would need to do different. Thanks for your help.2016-08-01 06:25 PM
Don't set Period to 0 or 1, put the bigger number in the Period, and the Smaller in Prescaler. Remember are both programed as N-1, ie where you want 6000 counts, you write 6000-1, ie 0..5999, has 6000 states.
You can write TIMx->ARR or TIMx->PSC directly, they are each single registers and can be written with a single action, don't reinitialize everything, it is pointless.2016-08-02 09:20 AM
That makes sense. I just needed to know the proper syntax.
I am noticing that setting the prescaler versus setting the period leads to a much cleaner timer value. For example, when I set the period to 1 and the prescaler to 36000 I get a clean square wave at 1000Hz (using an example program which turns the dac output to high and low at timer rate). When I set the prescaler to 1 and the period to 36000, the wave becomes extremely noisy and the frequency is unstable. Why is this?