ESP32-S3-Freertos,事件组和任务通知,ESP-IDF
·
事件组,简单来说是一个“数组”,每一个任务都可以对这个事件组进行置位,当有任务读取时,调用读取函数会返回当前的置位情况,返回值是整数类型
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "freertos/task.h"
#include "esp_log.h"
//本质还是 #define BIT0 0x00000001,整数类型
#define NUM0_BIT BIT0
#define NUM1_BIT BIT1
//创建事件句柄
static EventGroupHandle_t test_handle;
TaskHandle_t TaskA_Handle;
TaskHandle_t TaskB_Handle;
void TASKA(void *param){
while(1){
//设置事件组0位
xEventGroupSetBits(test_handle,NUM0_BIT);
vTaskDelay(pdMS_TO_TICKS(1000));
//设置事件组1位
xEventGroupSetBits(test_handle,NUM1_BIT);
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
void TASKB(void *param){
EventBits_t ev;
while (1)
{
//会返回当前事件组置位的编号,退出时清除
ev=xEventGroupWaitBits(test_handle,NUM0_BIT|NUM1_BIT,pdTRUE,pdFALSE,pdMS_TO_TICKS(5000));
if(ev==NUM0_BIT){
ESP_LOGI("xEvent0","wait0 true");
}
if(ev==NUM1_BIT){
ESP_LOGI("xEvent1","wait1 true");
}
}
}
void app_main(void)
{
//创建事件组
test_handle=xEventGroupCreate();
//创建任务
xTaskCreatePinnedToCore(TASKA,"TASKA",2048,NULL,3,&TaskA_Handle,1);
xTaskCreatePinnedToCore(TASKB,"TASKB",2048,NULL,3,&TaskB_Handle,1);
}
任务通知,与其余同步方式不同的是直接可以使用任务句柄进行通信
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
#include "freertos/task.h"
#include "esp_log.h"
TaskHandle_t TaskA_Handle;
TaskHandle_t TaskB_Handle;
void TASKA(void *param){
uint32_t value=0;
while(1){
//定时发送一个任务通知
//给任务B发送通知,任务B要先创建
xTaskNotify(TaskB_Handle,value,eSetValueWithOverwrite);
vTaskDelay(pdMS_TO_TICKS(1000));
value++;
}
}
void TASKB(void *param){
uint32_t value;
while (1)
{
//接受任务通知并打印
xTaskNotifyWait(0x00,ULONG_MAX,&value,pdMS_TO_TICKS(2000));
//32位用%ld 打印
ESP_LOGI("TASKB","receive value %ld",value);
}
}
void app_main(void)
{
//创建任务
xTaskCreatePinnedToCore(TASKB,"TASKB",2048,NULL,3,&TaskB_Handle,1);
xTaskCreatePinnedToCore(TASKA,"TASKA",2048,NULL,3,&TaskA_Handle,1);
}
更多推荐


所有评论(0)