Simvik

Drift-free periodic wake-up

Compute how long a periodic task should sleep so its period never drifts. A medium embedded C problem (RTOS scheduling), run and graded in the browser.

medium · RTOS scheduling · rtos · ticks · rollover

A task that runs its work and then sleeps for period ticks drifts: its period is really period plus however long the work took. RTOSes provide "delay until" instead, which wakes at fixed multiples of the period from a stored reference.

*last_wake is the tick at which the task last woke. Advance it by one period, and return how many ticks to sleep from now until then. If that time has already passed (the task overran), return 0; the next call will catch up.

The tick counter is 32 bits and may wrap. Less than one wrap ever separates *last_wake and now.

Starter code

uint32_t next_wake(uint32_t *last_wake, uint32_t period, uint32_t now) {
  *last_wake = now + period;
  return period;
}

Example tests

Sleep for the rest of the period

uint32_t last = 1000;
uint32_t a = next_wake(&last, 100, 1030);
uint32_t b = next_wake(&last, 100, 1105);
printf("%u %u %u\n", a, b, last);

Expected output:

70 95 1200

Catching up after an overrun

uint32_t last = 1000;
uint32_t a = next_wake(&last, 100, 1250);
uint32_t b = next_wake(&last, 100, 1250);
uint32_t c = next_wake(&last, 100, 1250);
printf("%u %u %u %u\n", a, b, c, last);

Expected output:

0 0 50 1300

Learn it first

More RTOS scheduling problems