micros() rollover period on Teensy 4.1

shookti

Active member
How much time ellapses before the micros() built-in function rolls over on a Teensy 4.1, and how to increase this time?
 
Micros returns a 32bit result. It overflows every 2^32 µs which is every 4.295E9 µs (=4295s = 71.6min). To prolong this you can store the value in the lower 32 bits of a 64bit variable. Then look periodically (at least once every 71min) if the read out value is smaller than the last one. In this case increment the high 32bit of the 64bit variable by 1. This will overflow in about 585000 years.
 
For most uses rollover is immaterial if you compare timestamps correctly and never want to wait too long, using the idiom:

Code:
if (micros() - previous_timestamp >= DELAY)
{
  previous_timestamp += DELAY;
  // do stuff
}
The key point is the subtraction before comparing - the result of the subtraction won't rollover unless DELAY is more than 32 bits.
 
So long as both sides of the comparison are cast to the same signed or unsigned type it should work, but unsigned is preferred.
 
Back
Top