This is how you create and use a task queue in FreeRTOS:
Global declaration
Declare the structure of a task (I recommend to use a task type enum class
in order to keep the flexibility of using multiple task types:
#include <freertos/queue.h> enum class I2CTaskType : uint8_t { MyTaskType = 0 }; struct I2CTask { I2CTaskType type; // Parameters int16_t value; }; static QueueHandle_t i2cTaskQueue;
Initialization code
Call this once, before using it:
// Create task queue i2cTaskQueue = xQueueCreate(8 /* Number of queue slots */, sizeof(I2CTask));
In the thread processing the queue
if (xQueueReceive(i2cTaskQueue, (void *)&task, portMAX_DELAY /* Wait infinitely for new tasks */) == pdTRUE) { if(task.type == I2CTaskType::MyTaskType) { // TODO process task Serial.printf("My task type: %d\r\n", task.value); } }
How to add a task to the queue
void AddTask(int16_t val) { I2CTask task; task.type = I2CTaskType::MyTaskType; task.value = val; xQueueSend(i2cTaskQueue, (void*)&task, 10 / portTICK_PERIOD_MS /* timeout */); }