Cooperative scheduler
Run periodic tasks from a table, the core of a super-loop. A hard embedded C problem (Timing, interrupts and concurrency), run and graded in the browser.
hard · Timing, interrupts and concurrency · scheduling · function-pointers · rollover
Many products have no RTOS: a table of tasks and a loop that runs whichever are due.
Go through the n entries of tasks in order. A task is due when at least period ticks have passed since last, which must work across tick rollover. Run each due task once and set its last to now. Skip entries whose run is NULL.
Starter code
void scheduler_tick(task_t *tasks, size_t n, uint32_t now) {
// Run every task whose period has elapsed, in table order.
}Example tests
Two tasks with different periods
task_t tasks[] = { { task_a, 10, 0 }, { task_b, 25, 0 } };
const uint32_t times[] = { 0, 10, 20, 25, 30, 50 };
ticks(tasks, 2, times, 6);Expected output:
|A|A|B|A|AB|A period of zero runs on every tick
task_t tasks[] = { { task_a, 0, 0 } };
const uint32_t times[] = { 0, 1, 2 };
ticks(tasks, 1, times, 3);Expected output:
A|A|A|Learn 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.
- 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.
- 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.