As simple as the timer TIM1 (not really)
Lets start with something "simple" yet still widely misundersood: standard timers in STM32.
STM32 microcontrollers have a unified timer periphery called "TIMx". This means that all timers with the same name, such as TIM2, will have the same functionality and registers, regardless of the MCU series. For example, TIM2 in STM32G474 will be functionally equivalent to TIM2 in STM32L052. That's cool, isn't it?
The most important timer parameters are the clock divider and the number it counts up to before it resets to zero. The clock divider is called the "Prescaler", and the number it counts up to is called the "Counter Period" or "Auto-reload Register". There is also a "Repetition Counter", but we will ignore it for now.
The value you enter in STM32CubeIDE is not quite what it sounds. Let's look at the formula from [1], page 11:
Update_event = TIM_CLK/((Prescaller + 1)*(Autoreload + 1)*(Repetition + 1))
As you can see, all of the registers have +1 added to their value. This means that when we set up the registers to get the precise value we want, we have to decrement the values by 1.
By the way, you can enter a simple formula to the field, so you can remember later why you have that wierd number, see the figure below:
The timer in this example has a system clock of 32 MHz. With the prescaller (32-1) we get 1 MHz clock to the timer input, and with (1000-1) we will get our trigger or interrupt fired with the frequency 1kHz.
Looks simple? Yeap. Nevertheless I saw many examples over the internet where people just enter desired values without the decrement. If you forget to decrement by 1, the timer will fire an interrupt or trigger event one cycle earlier than you intended. This may not seem like a big deal, but it can actually have a significant impact on the accuracy of your system. For example, if the Prescaler register has 32 instead of 31 in our example, there will be about 3% error that might be critical for some applications.
P.S. One more document that is a "must read" on timers is [2].
[1] AN4013 "STM32 cross-series timer overview" https://www.st.com/content/ccc/resource/technical/document/application_note/54/0f/67/eb/47/34/45/40/DM00042534.pdf/files/DM00042534.pdf/jcr:content/translations/en.DM00042534.pdf
[2] AN4776 "General-purpose timer cookbook for STM32 microcontrollers" https://www.st.com/resource/en/application_note/an4776-generalpurpose-timer-cookbook-for-stm32-microcontrollers-stmicroelectronics.pdf
Comments
Post a Comment