ESP32双核下WiFi协议栈与用户任务隔离配置指南

ESP32搭载双核Xtensa LX6,默认情况下FreeRTOS调度器允许任务在任意核心运行,WiFi协议栈任务与用户任务可能频繁切换核心,导致实时性下降、功耗增加甚至偶发看门狗复位。将WiFi协议栈固定到Core 0、用户任务绑定到Core 1,是提升系统稳定性的常用手段。

一、原理:核心亲和性与协议栈任务分布

  • ESP-IDF中每个任务通过xTaskCreatePinnedToCore()指定运行核心,或创建后用vTaskCoreAffinitySet()修改亲和性。
  • WiFi协议栈内部任务(如wifi、tiT、pp)默认由ESP-IDF配置为运行在Core 0(PRO CPU),但用户任务若未绑定,可能被调度到Core 0与协议栈竞争。
  • 双核隔离的核心思想:Core 0专用于协议栈与系统任务,Core 1专用于用户业务逻辑,减少跨核切换与缓存失效。
  • 注意:中断默认分配到Core 0,高频率GPIO中断可能干扰WiFi,需合理设置中断亲和性。

二、配置步骤

1. menuconfig关键选项

idf.py menuconfig
  • Component config → FreeRTOS → Run FreeRTOS only on first core:不要勾选,否则仅单核运行。
  • Component config → ESP32-specific → WiFi Task Core:确认WiFi任务核心为Core 0(默认)。
  • Component config → FreeRTOS → Task Watchdog Timeout:建议保持默认5秒,隔离后用户任务阻塞不会误触发看门狗。

2. 创建用户任务并绑定Core 1

使用xTaskCreatePinnedToCore(),最后一个参数指定核心号。

void app_main(void)
{
    // 初始化NVS、WiFi等(协议栈任务自动运行在Core 0)
    esp_err_t ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    wifi_init_sta();  // 内部创建WiFi任务,默认Core 0

    // 创建用户任务,绑定到Core 1
    xTaskCreatePinnedToCore(
        user_task,          // 任务函数
        "user_task",        // 任务名
        4096,               // 栈大小
        NULL,               // 参数
        5,                  // 优先级(低于WiFi任务通常为23)
        NULL,               // 任务句柄
        1                   // 核心号:1 = APP CPU
    );
}

3. 用户任务内避免阻塞式延时过长

void user_task(void *pvParameters)
{
    while (1) {
        // 业务逻辑:传感器采集、数据处理等
        printf("User task running on core %d\n", xPortGetCoreID());
        vTaskDelay(pdMS_TO_TICKS(1000));  // 释放CPU
    }
}

4. 中断亲和性设置(可选)

若用户任务依赖高频中断,可将中断绑定到Core 1,避免打断WiFi协议栈:

#include "esp_intr_alloc.h"
// 假设已获取中断句柄 intr_handle
esp_intr_set_core(intr_handle, 1);  // 绑定到Core 1

三、完整示例:双核隔离的WiFi STA + 用户任务

#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "nvs_flash.h"

static const char *TAG = "DUAL_CORE";

static void wifi_event_handler(void* arg, esp_event_base_t event_base,
                               int32_t event_id, void* event_data)
{
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
        esp_wifi_connect();
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
        ESP_LOGI(TAG, "Got IP, WiFi stack on core %d", xPortGetCoreID());
    }
}

void wifi_init_sta(void)
{
    esp_netif_init();
    esp_event_loop_create_default();
    esp_netif_create_default_wifi_sta();

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    esp_wifi_init(&cfg);

    esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, &wifi_event_handler, NULL);
    esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &wifi_event_handler, NULL);

    wifi_config_t wifi_config = {
        .sta = {
            .ssid = "YOUR_SSID",
            .password = "YOUR_PASS",
        },
    };
    esp_wifi_set_mode(WIFI_MODE_STA);
    esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config);
    esp_wifi_start();
}

void user_task(void *pvParameters)
{
    while (1) {
        ESP_LOGI(TAG, "User task on core %d, free heap: %d",
                 xPortGetCoreID(), esp_get_free_heap_size());
        vTaskDelay(pdMS_TO_TICKS(2000));
    }
}

void app_main(void)
{
    ESP_ERROR_CHECK(nvs_flash_init());
    wifi_init_sta();

    xTaskCreatePinnedToCore(user_task, "user_task", 4096, NULL, 5, NULL, 1);
}

四、注意事项

  • 优先级设置:用户任务优先级应低于WiFi任务(通常23),避免抢占协议栈导致连接不稳定。
  • 栈大小:Core 1任务栈需根据业务调整,默认4096字节可能不足,建议用uxTaskGetStackHighWaterMark()监控。
  • 共享资源保护:跨核访问全局变量需使用互斥锁或原子操作,ESP32双核非缓存一致,注意内存屏障。
  • 看门狗:若用户任务长时间阻塞,需在循环中喂狗或调用vTaskDelay。
  • 验证方法:通过xPortGetCoreID()打印任务核心,或使用esp_cpu_get_cycle_count()对比隔离前后WiFi吞吐量。

通过上述配置,WiFi协议栈与用户任务各占一核,系统实时性与稳定性显著提升,尤其适合音频流、电机控制等对时序敏感的场景。