8 years, 4 months ago.

Timer Overflow on STM32F303RE

Using a Timer on a Nucleo_F303RE overflows, as expected after the documented 2^31 -1 uS, however, when the value overflows, instead of wrapping around to zero, it jumps to -(2^31). This is because the timer used TIM2 counts to 2^32, and the ticker_api returns the value as a signed integer.

Is this the desired behaviour?

Question relating to:

1 Answer

8 years, 4 months ago.

Yes. If you prefer to have it overflow at 2^32-1 towards 0, just cast the signed integer to an unsigned integer. That is the magic of 2nd-complement binary counting :P. Binary wise it is the same.

Also if your counter is at 2^31-5, and 10 ticks later you read it again, so it is somewhere at minus alot, and you substract those two values, the end result will be 10 ticks.

While I know I *could* just cast the value of the timer to an unsigned, I am worried about the interface being inconsistent, causing portability issues across devices. Is this the behaviour on all other devices with 32bit timers, or do they overflow to 0?

posted by Eric Yanush 23 Nov 2015

The behavior is always the same, since they are always 32-bit timers, and because physically every 32-bit timer overflows like this. You would need to add extra code to make it overflow differently which really wouldn't be handy.

And honesty compells me to say once in a while there is a target again without a 32-bit timer which can run at 1us ticks, so a software timer is added to it to make it 32-bit. And once in a while they screw that up. But those are bugs, this is intended behavior.

posted by Erik - 24 Nov 2015