Skip to content
systemcoding.dev
RTOS

Pass context to a timer callback with pvTimerGetTimerID

Hand a timer callback its own context by storing a pointer as the timer ID and reading it back with pvTimerGetTimerID on FreeRTOS V11.2.0.

1 min read
Summarize in AI

A software timer callback receives only the timer's handle, so there is no argument to carry state. The timer ID is the escape hatch: xTimerCreate() takes a void * that the kernel stores untouched, and pvTimerGetTimerID() returns it inside the callback. One callback function can then serve many timers, each with its own context.

timer_ctx.cc
typedef struct { const char *name; int led; } blink_t;

static blink_t led_a = { "led-a", 2 };

static void on_expiry(TimerHandle_t t)
{
    blink_t *b = (blink_t *) pvTimerGetTimerID(t);
    printf("%s toggles pin %d\n", b->name, b->led);
}

void start(void)
{
    TimerHandle_t t = xTimerCreate("blink", pdMS_TO_TICKS(100), pdFALSE,
                                   &led_a, on_expiry);
    xTimerStart(t, 0);
}
Text
led-a toggles pin 2

The ID must outlive the timer: pass the address of a static or heap object, never a local. You can also replace it at run time with vTimerSetTimerID(), which is how a single timer can walk through states. Callbacks run in the timer service task, so keep them short and never block in them, as the timers header for Kernel V11.2.0 warns.

Taggedcfreertos
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.