开发板:NodeMCU 32 V1.3
开发环境:Arduino,https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
实现功能:
(1)设定2个任务,设定一个队列(常规或者静态)
(2)任务1:每隔1s,计数器加1,当计数值为5时,将计数值写入队列:xQueueSendToBack(myqueue, &count, wait_ticks)
,同时计数清零;
(3)任务2:等待接收队列, xQueueReceive(myqueue, &rec, portMAX_DELAY)
,第三个参数表示阻塞时间,如果这么长时间内没有接收到队列值,返回pdFALSE。
#include <Arduino.h>
#if CONFIG_FREERTOS_UNICORE
#define ARDUINO_RUNNING_CORE 0
#else
#define ARDUINO_RUNNING_CORE 1
#endif
/*创建静态队列*/
#define QUEUE_DEPTH 1
static StaticQueue_t qobj;
static uint8_t qstorage[QUEUE_DEPTH*sizeof(unsigned char)];
QueueHandle_t myqueue;
/* 任务函数声明 */
void SendQueue(void *pv);
void ReceiveQueue(void *pv);
/* Define the queue parameters. */
#define QUEUE_LENGTH 5
#define QUEUE_ITEM_SIZE sizeof( unsigned char )
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(115200);
/*获取程序使用的核*/
char app_cpu = xPortGetCoreID();
Serial.printf("Core used: %d\n", app_cpu);
//创建普通队列
myqueue = xQueueCreate(QUEUE_LENGTH, QUEUE_ITEM_SIZE);
//创建静态队列
// myqueue = xQueueCreateStatic(QUEUE_DEPTH,sizeof(unsigned char),&qstorage[0],&qobj);
//创建任务,注意stack size要大些,不然程序会一直reboot
//xTaskCreatePinnedToCore是esp32特有的,因为esp32有2个核,官方在原有freertos基础上进行了改进
xTaskCreatePinnedToCore(SendQueue, "SendQueue", 2048,NULL,1,NULL, ARDUINO_RUNNING_CORE);
xTaskCreatePinnedToCore(ReceiveQueue, "ReceiveQueue", 2048, NULL, 1, NULL, ARDUINO_RUNNING_CORE);
}
void loop()
{
// Empty. Things are done in Tasks.
vTaskDelete(NULL);
}
void SendQueue(void *pv)
{
unsigned char count=0;
TickType_t wait_ticks = 2;
for(;;)
{
count += 1;
if (count==5) //计数到5时,发送队列
{
Serial.printf(">>> Start to send queue!\n", count);
BaseType_t rc = xQueueSendToBack(myqueue, &count, wait_ticks); // send queue
if (rc==pdTRUE) Serial.printf("Count:%d, Send from SendQueue!\n", count);
else Serial.println("Error sending queue!");
count = 0; //计数清零
}
vTaskDelay(1000); //每隔1s数值增一
}
}
void ReceiveQueue(void *pv)
{
unsigned char rec;
const TickType_t wait=120; //队列接收等待时间,超过该时间还没接收到队列数据返回pdFALSE
for(;;)
{
//接收队列阻塞时间:portMAX_DELAY,表示当队列为空时一直阻塞
BaseType_t rc = xQueueReceive(myqueue, &rec, portMAX_DELAY);
if (rc==pdTRUE) Serial.printf("Received:%d, Message from ReceiveQueue!\n", rec);
else Serial.println("Error receiving queue!");
vTaskDelay(1000);
}
}
效果如下: