Pass a struct to a FreeRTOS task through pvParameters
Hand a configuration struct to a new FreeRTOS task through the pvParameters pointer, and keep the struct alive for the task's whole life.
xTaskCreate() gives a task one void * argument, and the clean way to pass several settings is a struct. The catch is lifetime: the task keeps that pointer for as long as it runs, so the struct must outlive the function that created the task. Pass the address of a static object, not of a local variable.
#include "FreeRTOS.h"
#include "task.h"
#include <stdio.h>
typedef struct { const char *label; uint32_t period_ms; } blink_cfg_t;
static void blink_task(void *pv)
{
const blink_cfg_t *cfg = (const blink_cfg_t *)pv;
for (;;) {
printf("%s every %lu ms\n", cfg->label, (unsigned long)cfg->period_ms);
vTaskDelay(pdMS_TO_TICKS(cfg->period_ms));
}
}
void app_start(void)
{
static const blink_cfg_t red = { "red", 500u };
static const blink_cfg_t green = { "green", 800u };
xTaskCreate(blink_task, "red", 256, (void *)&red, 1, NULL);
xTaskCreate(blink_task, "green", 256, (void *)&green, 1, NULL);
vTaskStartScheduler();
}red every 500 ms
green every 800 ms
red every 500 msThe two tasks share one function and differ only by the pointer they get, which is the usual reason to reach for this. The output ordering shown is the first lines after the scheduler starts; later lines interleave by period. If red were a local variable in app_start(), the scheduler would hand the task a dangling pointer the moment that function returned, and since vTaskStartScheduler() normally never returns, the bug only appears when something else reuses that stack. Casting away const for the call is fine because the task treats it as read-only. The stack depth argument is in words, not bytes. This follows the FreeRTOS Kernel 11.1 API.