Implement a run-to-completion cooperative scheduler table
Drive a list of periodic jobs from one table and a single dispatcher loop, no stacks per task and no context switch, in plain C on any MCU.
A cooperative run-to-completion scheduler is a table of function pointers and a loop. Each entry has a period and a last-run time, and the dispatcher calls whatever is due. There is no stack per task because every job returns before the next one starts, which is why this fits in a few hundred bytes of RAM and why it needs no assembly.
#include <stdint.h>
typedef struct {
void (*run)(void);
uint32_t period_ms;
uint32_t last_ms;
} job_t;
extern volatile uint32_t ms_ticks; // bumped by SysTick_Handler
extern void led_task(void), uart_task(void), adc_task(void);
static job_t jobs[] = {
{ led_task, 500u, 0u },
{ uart_task, 10u, 0u },
{ adc_task, 25u, 0u },
};
void sched_run(void)
{
for (;;) {
uint32_t now = ms_ticks;
for (unsigned i = 0; i < sizeof jobs / sizeof jobs[0]; i++) {
if ((uint32_t)(now - jobs[i].last_ms) >= jobs[i].period_ms) {
jobs[i].last_ms = now;
jobs[i].run();
}
}
}
}The subtraction now - jobs[i].last_ms is done in unsigned 32-bit arithmetic, so it stays correct when the millisecond counter wraps, which takes about 49.7 days. Comparing now >= last + period instead breaks at the wrap. The table order is your priority order, because a due job earlier in the table runs first, and a slow job delays everything after it. Keep each job short, split long work into steps, and reach for a preemptive kernel when you cannot guarantee that.