ESP32 event 事件发布和处理

原版的example比较复杂,为搞清其关系,简化流程。使用default的loop。我的理解是如果想提高优先级,可以独立建一个loop。 

/* esp_event (event loop library) basic example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_event_base.h"
#include "esp_event.h"
#include "esp_timer.h"

// Declarations for the event source
#define TASK_ITERATIONS_COUNT        10      // number of times the task iterates
#define TASK_PERIOD                  500     // period of the task loop in milliseconds


enum {
    TASK_ITERATION_EVENT ,                    // raised during an iteration of the loop within the task
    TASK_WIFI_OK_EVENT ,                    // raised during an iteration of the loop within the task
};

static const char* TAG = "user_event_loops";

/* Event source task related definitions */
ESP_EVENT_DEFINE_BASE(TASK_EVENTS);


static void task_handler(void* handler_args, esp_event_base_t event_base, int32_t event_id, void* event_data)
{    
    int value = *((int*) event_data);

    ESP_LOGI(TAG, "handler_args:%p, event_base:%p, id(%d) value %d", handler_args, event_base, event_id, value);
}


/* Example main */
void app_main(void)
{
    int value = 99;
    ESP_LOGI(TAG, "setting up");
    int event_handler_arg = 123;

    ESP_ERROR_CHECK(esp_event_loop_create_default());   
    ESP_ERROR_CHECK(esp_event_handler_instance_register(TASK_EVENTS, TASK_ITERATION_EVENT, task_handler, &event_handler_arg, NULL));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(TASK_EVENTS, TASK_WIFI_OK_EVENT, task_handler, &event_handler_arg, NULL));

    ESP_LOGI(TAG, "starting event source, %p,%p", &event_handler_arg, TASK_EVENTS);  

    ESP_ERROR_CHECK(esp_event_post(TASK_EVENTS, TASK_ITERATION_EVENT, &value, sizeof(value), portMAX_DELAY));
    vTaskDelay(pdMS_TO_TICKS(2000));
    value += 22;

    ESP_ERROR_CHECK(esp_event_post(TASK_EVENTS, TASK_WIFI_OK_EVENT, &value, sizeof(value), portMAX_DELAY));
    vTaskDelay(pdMS_TO_TICKS(2000));
    value += 22;

    ESP_ERROR_CHECK(esp_event_post(TASK_EVENTS, TASK_ITERATION_EVENT, &value, sizeof(value), portMAX_DELAY));
    vTaskDelay(pdMS_TO_TICKS(2000));
    value += 22;

    ESP_ERROR_CHECK(esp_event_post(TASK_EVENTS, TASK_WIFI_OK_EVENT, &value, sizeof(value), portMAX_DELAY));

  
}

你可能感兴趣的:(esp32,物联网,iot,c语言,esp32)