Implement a software timer module.
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
typedef void (*timer_cb_t)(void *arg);
typedef struct { uint32_t expiry, period; timer_cb_t cb; void *arg; bool active; } swtimer_t;
#define MAX_TIMERS 8
static swtimer_t timers[MAX_TIMERS];
extern volatile uint32_t g_ms; /* 1 ms tick */
int timer_start(uint32_t delay_ms, uint32_t period_ms, timer_cb_t cb, void *arg)
{
for (int i = 0; i < MAX_TIMERS; i++) {
if (!timers[i].active) {
timers[i] = (swtimer_t){ g_ms + delay_ms, period_ms, cb, arg, true };
return i; /* handle */
}
}
return -1;
}
void timer_stop(int h) { if (h >= 0 && h < MAX_TIMERS) timers[h].active = false; }
void timer_poll(void) /* call from the main loop / a timer task */
{
uint32_t now = g_ms;
for (int i = 0; i < MAX_TIMERS; i++) {
swtimer_t *t = &timers[i];
if (t->active && (int32_t)(now - t->expiry) >= 0) { /* wrap-safe "now >= expiry" */
if (t->period) t->expiry += t->period; /* periodic: no drift */
else t->active = false; /* one-shot */
t->cb(t->arg);
}
}
}
Points: wrap-safe comparison with signed difference; periodic timers add the period to the old expiry (not to "now") so they do not drift; callbacks run in the main loop, not in the tick ISR, so they can take time (but must not block). Scaling up: keep timers in a list sorted by expiry (or a timer wheel) so each tick checks only the first one, and program a hardware timer for the next expiry (tickless) to save power. RTOS equivalents: FreeRTOS software timers (run in the timer service task), Zephyr k_timer.