AnsweredAssumed Answered

[TIM] Delay needed between setting event through EGR and clearing SR

Question asked by waclawek.jan on Apr 29, 2018

This problem has been discovered by Sanjay Kumawat .

 

In STM32 timer (TIM), when the Update Event is forced by setting TIM_EGR. UG (for example to "activate" the newly set prescaler value), TIM_SR.UIF is set as a consequence, and that in turn triggers an interrupt as soon as enabled by TIM_DIER.UIE. This is sometimes undesirable, so TIM_SR.UIF has to be cleared before the interrupts are enabled in TIM_DIER.

 

However, if TIM_SR is written too soon after writing TIM_EGR, the relevant flag in TIM_SR is not cleared and results in unwanted interrupt.

 

The program in attachment (for gcc and the L476 DISCO) demonstrates the problem. To avoid compiler influence, the critical sequence is written in inline asm. There are two workarounds presented there: three NOPs, or one write to an unrelated TIM3 register, in between writing to EGR and SR. If at least one NOP is removed, or in the other case the write to the unrelated register is removed, the interrupt is invoked immediately after enabling, demonstrated by the red LED lighting up immediately after reset; otherwise, the correct behaviour is, that the red LED lights up for the first time only after the timer's first full cycle elapsed, i.e. after cca 1 seconds (the 'L476 runs at its default 4MHz MSI clock).

 

While the "write to TIM register" is a better solution than the NOPs (because the write may be done into a "useful" register, e.g. ARR), both are imperfect in that they rely on particular timing between the processor and the timer (e.g. when APB divider is set to non-1, more NOPs will be needed; and the write-to-register IMO relies on the syncrhonization delays in the AHB-to-APB bridge which may also be influenced by different APB divider).

 

I also believe this is pertinent not only to the Update Event, but any other events which can be set by TIM_EGR.

 

ST, please comment.

 

Thanks,

 

Jan Waclawek

Attachments

Outcomes