</>EmbeddedInterview

Implement a simple cooperative task scheduler.

Medium"Coding: Embedded Drivers, Buffers & Schedulers"
#include <stdint.h>

typedef struct {
    void (*run)(void);
    uint32_t period_ms;
    uint32_t next_ms;
} task_t;

static void task_led(void);
static void task_sensor(void);
static void task_comms(void);

static task_t tasks[] = {
    { task_led,     500, 0 },
    { task_sensor,   10, 0 },
    { task_comms,     1, 0 },
};

extern volatile uint32_t g_ms;

void scheduler_run(void)
{
    for (;;) {
        uint32_t now = g_ms;
        for (unsigned i = 0; i < sizeof tasks / sizeof tasks[0]; i++) {
            if ((int32_t)(now - tasks[i].next_ms) >= 0) {
                tasks[i].next_ms += tasks[i].period_ms;    /* fixed rate */
                tasks[i].run();                            /* must return quickly: no blocking */
            }
        }
        /* __WFI();  sleep until the next tick interrupt */
    }
}

Points: each task is a function that does a small amount of work and returns (long jobs become state machines); tasks run in table order, so order sets priority on ties; the worst-case response time is the sum of the longest task runs, so measure task execution times; no task stacks or context switches, so it is tiny and easy to debug. Add an overrun check (next_ms falling behind now) to detect overload. When you need pre-emption or blocking APIs, move to an RTOS.