FreeRTOS 任务队列最小示例
这是你在 FreeRTOS 中创建和使用任务队列的方法:
全局声明
声明任务的结构(我建议使用*任务类型 enum class*以保持使用多种任务类型的灵活性:
freertos_i2c_task_structs.cpp
#include <freertos/queue.h>
enum class I2CTaskType : uint8_t {
MyTaskType = 0
};
struct I2CTask {
I2CTaskType type;
// 参数
int16_t value;
};
static QueueHandle_t i2cTaskQueue;初始化代码
在使用之前调用一次:
i2cTaskQueue = xQueueCreate(8 /* Number of queue slots */, sizeof(I2CTask));
freertos_i2c_queue_init.cpp
// 创建任务队列
i2cTaskQueue = xQueueCreate(8 /* Number of queue slots */, sizeof(I2CTask));在处理队列的线程中
freertos_i2c_queue_receive.cpp
if (xQueueReceive(i2cTaskQueue, (void *)&task, portMAX_DELAY /* Wait infinitely for new tasks */) == pdTRUE) {
if(task.type == I2CTaskType::MyTaskType) {
// TODO 处理任务
Serial.printf("My task type: %d\r\n", task.value);
}
}如何向队列添加任务
freertos_i2c_add_task.cpp
void AddTask(int16_t val) {
I2CTask task;
task.type = I2CTaskType::MyTaskType;
task.value = val;
xQueueSend(i2cTaskQueue, (void*)&task, 10 / portTICK_PERIOD_MS /* timeout */);
}Check out similar posts by category:
C/C++, Embedded, FreeRTOS, PlatformIO
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow