cancel
Showing results for 
Search instead for 
Did you mean: 

Setting Up Variable Speed Timer on STM32F4

epalaima
Associate II
Posted on August 01, 2016 at 20:55

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 #!stm32
4 REPLIES 4
Posted on August 01, 2016 at 21:27

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.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
epalaima
Associate II
Posted on August 01, 2016 at 23:43

So would that mean to change one of them I could simply put: 

timerInitStructure.TIM_Prescaler = 6000;

or

timerInitStructure.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.

Posted on August 02, 2016 at 03:25

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.

Tips, Buy me a coffee, or three.. PayPal Venmo
Up vote any posts that you find helpful, it shows what's working..
epalaima
Associate II
Posted on August 02, 2016 at 18:20

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?