Elapsed time across rollover
Compute how many ticks have passed, even when the counter has wrapped. An easy embedded C problem (Timing, interrupts and concurrency), run and graded in the…
easy · Timing, interrupts and concurrency · ticks · rollover
A 32-bit millisecond counter wraps to 0 after about 49.7 days. Code that runs for months must give the right answer across that wrap.
Return the number of ticks from start to now. now is always the later reading, and less than one full wrap has passed.
Starter code
uint32_t elapsed(uint32_t now, uint32_t start) {
// "Defensive" check that breaks at rollover.
if (now < start) return 0;
return now - start;
}Example tests
No rollover
printf("%u\n", elapsed(1000, 400));Expected output:
600Counter wrapped between the readings
printf("%u\n", elapsed(5, 0xFFFFFFF0));Expected output:
21Learn it first
- Interrupts, timing and concurrency · How interrupts work on a Cortex-M, priorities, latency, races, rollover-safe time, non-blocking code and debouncing.
More Timing, interrupts and concurrency problems
- Rollover-safe timeout · Decide whether a timeout has expired without being fooled by wrap-around.
- Non-blocking blink · Derive an LED state from the current time instead of calling delay.
- Milliseconds to ticks · Convert a delay in milliseconds to RTOS ticks, rounding up.
- Debounce a button · Accept a new button state only after it has been stable for several samples.
- Periodic software timer · Fire once per period without drift and across counter rollover.
- Protect a shared variable · Make a read-modify-write safe from interrupts, and safe to nest.
- Cooperative scheduler · Run periodic tasks from a table, the core of a super-loop.
- Driver: measure worst-case time with the cycle counter · Enable the Cortex-M cycle counter and time a function across many runs, wraparound included.
- Smart lock: relock after 30 seconds · Relock automatically, with time arithmetic that survives the millisecond counter wrapping.