ESP32 FreeRTOS队列操作

开发板: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);
  }
}

效果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值