使用 xQueueSend函数一次性推送多个变量的示例代码
时间: 2024-05-13 17:15:44 浏览: 11
下面是使用 `xQueueSend` 函数一次性推送多个变量的示例代码:
```c
#include <stdio.h>
#include "FreeRTOS.h"
#include "task.h"
#include "queue.h"
#define QUEUE_LENGTH 5
#define ITEM_SIZE sizeof(int) + sizeof(float) + sizeof(char)
QueueHandle_t xQueue;
void sender_task(void *pvParameters)
{
int int_data = 10;
float float_data = 3.14;
char char_data = 'A';
while (1) {
// 分配内存空间
void *buf = pvPortMalloc(ITEM_SIZE);
memcpy(buf, &int_data, sizeof(int));
memcpy(buf + sizeof(int), &float_data, sizeof(float));
memcpy(buf + sizeof(int) + sizeof(float), &char_data, sizeof(char));
// 发送数据到队列
xQueueSend(xQueue, buf, 0);
// 释放内存空间
vPortFree(buf);
// 暂停一段时间
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
void receiver_task(void *pvParameters)
{
while (1) {
// 从队列接收数据
void *buf = pvPortMalloc(ITEM_SIZE);
if (xQueueReceive(xQueue, buf, portMAX_DELAY) == pdTRUE) {
int int_data;
float float_data;
char char_data;
// 解析数据
memcpy(&int_data, buf, sizeof(int));
memcpy(&float_data, buf + sizeof(int), sizeof(float));
memcpy(&char_data, buf + sizeof(int) + sizeof(float), sizeof(char));
// 输出数据
printf("Received: %d, %f, %c\n", int_data, float_data, char_data);
}
// 释放内存空间
vPortFree(buf);
}
}
int main(void)
{
// 创建队列
xQueue = xQueueCreate(QUEUE_LENGTH, ITEM_SIZE);
if (xQueue == NULL) {
printf("Failed to create queue\n");
return 0;
}
// 创建发送任务
xTaskCreate(sender_task, "Sender", 1024, NULL, 1, NULL);
// 创建接收任务
xTaskCreate(receiver_task, "Receiver", 1024, NULL, 1, NULL);
// 启动调度器
vTaskStartScheduler();
return 0;
}
```
在此示例中,我们定义了一个 `ITEM_SIZE` 常量来表示每个数据项的大小,它包含一个整数、一个浮点数和一个字符。然后在发送任务中,我们分配内存空间并使用 `memcpy` 函数将三个变量拷贝到内存空间中,然后将整个内存空间发送到队列中。在接收任务中,我们从队列接收数据,并使用 `memcpy` 函数将内存空间中的数据拷贝到三个变量中,然后输出这三个变量的值。注意,在每个任务中我们都使用 `pvPortMalloc` 函数分配内存空间,并使用 `vPortFree` 函数释放内存空间,这是因为 FreeRTOS 建议使用这些函数来管理内存空间,以避免内存泄漏问题。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)