Message Queue in RTOS in Embedded C: What It Is and How It Works
message queue in an RTOS is a communication tool that lets tasks send and receive messages safely and in order. It acts like a mailbox where tasks can put messages and other tasks can pick them up, helping coordinate work in embedded C programs.How It Works
Imagine a message queue as a line at a post office where letters (messages) are placed by one person (task) and picked up by another. In an RTOS, tasks run independently and may need to share information. The message queue stores these messages in a safe order so no message is lost or mixed up.
When a task sends a message, it puts it into the queue. Another task waits for messages and takes them out one by one. The RTOS manages this process so tasks don’t interfere with each other, even if they run at the same time. This helps keep the system organized and responsive.
Example
This example shows two tasks: one sends numbers to the message queue, and the other receives and prints them.
#include "FreeRTOS.h" #include "task.h" #include "queue.h" #include <stdio.h> QueueHandle_t xQueue; void SenderTask(void *pvParameters) { int count = 0; while (1) { xQueueSend(xQueue, &count, portMAX_DELAY); printf("Sent: %d\n", count); count++; vTaskDelay(pdMS_TO_TICKS(1000)); } } void ReceiverTask(void *pvParameters) { int receivedValue; while (1) { if (xQueueReceive(xQueue, &receivedValue, portMAX_DELAY) == pdPASS) { printf("Received: %d\n", receivedValue); } } } int main(void) { xQueue = xQueueCreate(5, sizeof(int)); if (xQueue == NULL) { printf("Queue creation failed!\n"); return 1; } xTaskCreate(SenderTask, "Sender", 1000, NULL, 1, NULL); xTaskCreate(ReceiverTask, "Receiver", 1000, NULL, 1, NULL); vTaskStartScheduler(); return 0; }
When to Use
Use message queues in RTOS when tasks need to share data or signals without interfering with each other. They are perfect for passing commands, sensor data, or status updates between tasks.
For example, in an embedded system controlling a robot, one task might read sensors and send data through a message queue, while another task processes that data to make decisions. This keeps tasks independent and the system stable.
Key Points
- Message queues help tasks communicate safely in RTOS.
- They store messages in order until the receiving task is ready.
- Queues prevent data loss and race conditions.
- They are useful for passing data or signals between tasks.