Simvik

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 0

A 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 1

Learn it first

More Timing, interrupts and concurrency problems