ESP32 S3 基于开发框架(Arduino)使用FreeRTOS队列

444 阅读1分钟

1 使用FreeRTOS队列

/*
//  多线程基于FreeRTOS,可以多个任务并行处理;
//  ESP32具有两个32位Tensilica Xtensa LX6微处理器;
//  实际上我们用Arduino进行编程时只使用到了第一个核(大核),第0核并没有使用
//  多线程可以指定在那个核运行;
 */

#include <Arduino.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define USE_MULTCORE 1
QueueHandle_t xQueue;

void xTaskOne(void *xTask1)
{
    while (1)
    {
        USBSerial.printf("Task1 \r\n");
        delay(500);
    }
}

void xTaskTwo(void *xTask2)
{
    while (1)
    {
        USBSerial.printf("Task2 \r\n");
        delay(1000);
    }
}

//发送任务
 void Send_Task(void *arg)
 {
     // 初始化
     int i = 0;
     // 循环
     while (1)
     {
         // printf("Send task! i = %d.\n", i++);
         if (xQueueSend(xQueue, (void *)&i, 0) == pdPASS)
         {
             USBSerial.printf("Send!\n");
         }
         else
         {
             USBSerial.printf("Cannot send!\n");
         }
         i++;
         vTaskDelay(1000 / portTICK_RATE_MS);
     }
 }

 //接受任务
 void Rce_Task(void *arg)
 {
     // 初始化
     int j;
     // 循环
     while (1)
     {
         if (xQueueReceive(xQueue, (void *)&j, 0) == pdPASS)
         {
             USBSerial.printf("Rce ! j = %d.\n", j);
         }
         vTaskDelay(1000 / portTICK_RATE_MS);
     }
 }

 //测试用的主函数
 void app_main(void)
 {

     xQueue = xQueueCreate(10, sizeof(int));
     if (xQueue == NULL)
     {
         /* The queue could not be created. */
         USBSerial.printf("The queue cannot be created !\n");
     }
     else
     {
         xTaskCreate(Send_Task, "Send_Task", 2048, NULL, 1, NULL);
         xTaskCreate(Rce_Task, "Rce_Task", 2048, NULL, 1, NULL);
     }
 }
 
void setup()
{
    USBSerial.begin(115200);
    app_main();
}

void loop()
{

}