多任务发送,一任务接收。
#include <stdio.h> #include "sdkconfig.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "freertos/queue.h" #include "esp_system.h" #include "esp_spi_flash.h" void sendtask1(void *pvParam); void sendtask2(void *pvParam); void rectask1(void *pvParam); typedef struct iQueueStruct { char id; uint16_t data; } xStruct; void sendtask1(void *pvParam) { QueueHandle_t QHandle; QHandle = (QueueHandle_t)pvParam; BaseType_t xStatus; xStruct xdata = {0, 26}; while (true) { xStatus = xQueueSend(QHandle, &xdata, 0); if (xStatus != pdPASS) printf("send fial!\n"); else printf("data was sent!\n"); xdata.id++; vTaskDelay(1000 / portTICK_PERIOD_MS); } } void sendtask2(void *pvParam) { QueueHandle_t QHandle; QHandle = (QueueHandle_t)pvParam; BaseType_t xStatus; char *pStrTosend; int i = 0; pStrTosend = (char *)malloc(50); while (true) { i++; sprintf(pStrTosend, "it is good times%d\n", i); xStatus = xQueueSend(QHandle, &pStrTosend, 0); if (xStatus != pdPASS) printf("send fial!\n"); else printf("data was sent!\n"); vTaskDelay(1000 / portTICK_PERIOD_MS); } } void rectask1(void *pvParam) { QueueHandle_t QHandle; QHandle = (QueueHandle_t)pvParam; BaseType_t xStatus; xStruct xdata = {0, 0}; char *RecTopStr; while (true) { xStatus = xQueueReceive(QHandle, &xdata, portMAX_DELAY); //添加阻塞,就不需要另外阻塞 xStatus = xQueueReceive(QHandle, &RecTopStr, portMAX_DELAY); if (xStatus != pdPASS) printf("rec fail\n"); else printf("rec id is %d,data is %d, pstr is %s\n", xdata.id, xdata.data, RecTopStr); } } void app_main(void) { QueueHandle_t iQueueStatus; iQueueStatus = xQueueCreate(50, sizeof(int)); if (iQueueStatus != NULL) { printf("Queue was created!"); xTaskCreate(sendtask1, "task1", 1024 * 4, (void *)iQueueStatus, 1, NULL); xTaskCreate(sendtask2, "task2", 1024 * 4, (void *)iQueueStatus, 1, NULL); xTaskCreate(rectask1, "task3", 1024 * 4, (void *)iQueueStatus, 2, NULL);//接收的优先级要高于发送的优先级。 /* code */ } while (true) { vTaskDelay(1000 / portTICK_PERIOD_MS); } }
发送任务的优先级要低于接收任务的优先级。
因为接收任务优先级高,所以它在没有接收到数据的时候会一直在阻塞状态,让低优先级的任务先运行。接收到数据后会继续运行。所以我没有在接收函数中放置阻塞函数。
实验现象: