Skip to content
systemcoding.dev
RTOS

Create a queue of structs with xQueueCreate and sizeof

Pass whole structs between FreeRTOS tasks by value with xQueueCreate and sizeof, so the sender's copy can change right after the send.

2 min read
Summarize in AI

A FreeRTOS queue copies items in and out by value. Give xQueueCreate() the length and sizeof of your struct, and every send copies that many bytes into the queue's storage. The sender can reuse its variable the moment xQueueSend() returns.

sensor_q.cc
typedef struct { uint8_t id; int16_t temp_c10; } reading_t;

static QueueHandle_t q;

static void producer(void *arg)
{
    (void)arg;
    reading_t r = { 1, 215 };
    xQueueSend(q, &r, portMAX_DELAY);
    r.id = 2; r.temp_c10 = 198;           // safe: the queue holds a copy
    xQueueSend(q, &r, portMAX_DELAY);
    vTaskDelete(NULL);
}

static void consumer(void *arg)
{
    (void)arg;
    reading_t r;
    while (xQueueReceive(q, &r, pdMS_TO_TICKS(100)) == pdTRUE)
        printf("id %u: %d.%d C\n", r.id, r.temp_c10 / 10, r.temp_c10 % 10);
    vTaskDelete(NULL);
}

void app_start(void)
{
    q = xQueueCreate(4, sizeof(reading_t));
    configASSERT(q != NULL);
    xTaskCreate(producer, "prod", 256, NULL, 2, NULL);
    xTaskCreate(consumer, "cons", 256, NULL, 1, NULL);
}
Text
id 1: 21.5 C
id 2: 19.8 C

Pass sizeof(reading_t) rather than a hard-coded number, so the queue follows the struct when you add a field. Storage is length * item_size bytes plus the queue header, and it comes from the FreeRTOS heap, so xQueueCreate() returns NULL when the heap is exhausted; check it. The tradeoff of copy semantics is cost: a 200-byte struct is copied twice per message. For large payloads, queue a pointer to a buffer from a pool and transfer ownership explicitly. The behavior is the same in FreeRTOS Kernel 11.1.

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.