Periodic software timer
Fire once per period without drift and across counter rollover. A medium embedded C problem (Timing, interrupts and concurrency), run and graded in the browser.
medium · Timing, interrupts and concurrency · timers · rollover · drift
The main loop polls a software timer with the current tick count.
Return true when at least period ticks have passed since start, and in that case advance start by exactly one period. Advancing by the period, instead of setting start to now, keeps the long-term rate exact even when polls arrive late. The comparison must be correct across tick rollover.
Starter code
bool timer_poll(soft_timer_t *t, uint32_t now) {
// True once per period; advance t->start by t->period each time it fires.
return false;
}Example tests
Fires once per period
soft_timer_t t = { 0, 100 };
const uint32_t times[] = { 50, 100, 150 };
polls(&t, times, 3);Expected output:
0 1 0A late poll does not shift later periods
soft_timer_t t = { 0, 100 };
const uint32_t times[] = { 100, 210, 290, 300 };
polls(&t, times, 4);Expected output:
1 1 0 1Learn 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
- Elapsed time across rollover · Compute how many ticks have passed, even when the counter has wrapped.
- 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.
- 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.