Mastering ESP32 Wi-Fi Event Handling for Reliable IoT

For IoT devicesConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies., robust Wi-FiArquitetura ESP32: SoC dual-core, subsistemas RF integradosArquitetura ESP32: SoC dual-core, subsistemas RF integradosDiscover the ESP32’s dual-core prowess and integrated RF subsystems for efficient, innovative IoT applications—from smart homes to industrial sensors. event handling is non-negotiable. Whether it’s a smart thermostat losing connectivity during a firmware update or an industrial sensor needing to reconnect autonomously, understanding Wi-Fi events ensures reliability. This guide dives deep into ESP32’s event-driven architecture, with practical code examples and real-world use casesZigbee Green Power: Ultra-Low-Power Energy Harvesting SolutionsZigbee Green Power: Ultra-Low-Power Energy Harvesting SolutionsDiscover how ZGP enables battery-free IoT devices through energy harvesting with ESP32 integrations, supporting smart home and industrial applications..

Table of Contents🔗

Understanding Wi-Fi Events🔗

Wi-Fi events are system-generated notifications that occur when specific Wi-FiArquitetura ESP32: SoC dual-core, subsistemas RF integradosArquitetura ESP32: SoC dual-core, subsistemas RF integradosDiscover the ESP32’s dual-core prowess and integrated RF subsystems for efficient, innovative IoT applications—from smart homes to industrial sensors.-related actions take place, such as connecting to a network, losing connection, or encountering errors. These events are essential for maintaining a stable connection and responding to changes in the network environment.

The ESP32Setting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips. SDK provides a set of predefined Wi-Fi event IDs, which you can use to trigger custom event handlers. By leveraging these events, you can ensure your application reacts appropriately to connectivity changes.

Common Wi-Fi Events on ESP32🔗

The ESP32 supports a wide rangeQuick Comparison: Range, power consumption, costs, and complexity of each technologyQuick Comparison: Range, power consumption, costs, and complexity of each technologyDiscover the ideal wireless solution for your ESP32 IoT project by analyzing range, power, cost, and complexity. Optimize connectivity now. of Wi-Fi events. Here are some of the most common ones:

Event IDDescription
SYSTEM_EVENT_STA_STARTStation mode started
SYSTEM_EVENT_STA_CONNECTEDConnected to a Wi-Fi access point
SYSTEM_EVENT_STA_DISCONNECTEDDisconnected from the Wi-Fi access point
SYSTEM_EVENT_STA_AUTHMODE_CHANGEAuthentication mode of the access point changed
SYSTEM_EVENT_STA_GOT_IPObtained an IP address from the access point
SYSTEM_EVENT_STA_LOST_IPLost the IP address
SYSTEM_EVENT_AP_STARTAccess point mode started
SYSTEM_EVENT_AP_STOPAccess point mode stopped

These events are part of the esp_event library, which provides a unified event-handling mechanism for the ESP32Setting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips..

Setting Up Wi-Fi Event Handlers🔗

To handle Wi-FiArquitetura ESP32: SoC dual-core, subsistemas RF integradosArquitetura ESP32: SoC dual-core, subsistemas RF integradosDiscover the ESP32’s dual-core prowess and integrated RF subsystems for efficient, innovative IoT applications—from smart homes to industrial sensors. events, you need to register an event handler function. This function will be called whenever a specific event occurs. Here’s how to set it up:

Arduino Framework Example

#include <WiFi.h>
void WiFiEventHandler(WiFiEvent_t event) {
    switch (event) {
        case SYSTEM_EVENT_STA_CONNECTED:
            Serial.println("Connected to Wi-Fi!");
            break;
        case SYSTEM_EVENT_STA_DISCONNECTED:
            Serial.println("Disconnected from Wi-Fi!");
            break;
        case SYSTEM_EVENT_STA_GOT_IP:
            Serial.println("Obtained IP address!");
            break;
        default:
            break;
    }
}
void setup() {
    Serial.begin(115200);
    WiFi.onEvent(WiFiEventHandler); // Register the event handler
    WiFi.begin("YourSSID", "YourPassword");
}
void loop() {
    // Your main code here
}

ESP-IDF Example

#include "esp_event.h"
#include "esp_wifi.h"
void wifi_event_handler(void* arg, esp_event_base_t base, int32_t id, void* data) {
    if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED) {
        esp_wifi_connect(); // Immediate reconnect attempt
    }
}
void app_main() {
    esp_event_loop_create_default();
    esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, wifi_event_handler, NULL);
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    esp_wifi_init(&cfg);
    esp_wifi_set_mode(WIFI_MODE_STA);
    esp_wifi_start();
    esp_wifi_connect();
}

Handling Events in Arduino Framework🔗

The Arduino coreZigbee Over-the-Air (OTA) Firmware Updates with ESP32 CoordinatorsZigbee Over-the-Air (OTA) Firmware Updates with ESP32 CoordinatorsSecure your IoT network with OTA firmware upgrades using an ESP32 coordinator. Our guide details firmware setup, packaging, security, and troubleshooting. for ESP32 simplifies event handling with WiFiImplementing Over-the-Air (OTA) Updates via Wi-Fi on ESP32Implementing Over-the-Air (OTA) Updates via Wi-Fi on ESP32Learn how to implement secure and reliable OTA updates on ESP32 for enhanced IoT performance, easy updates, and rollback capability without physical access..onEvent().

Example: Logging Connection State Changes

void wifiEventHandler(WiFiEvent_t event, WiFiEventInfo_t info) {
    switch (event) {
        case SYSTEM_EVENT_STA_CONNECTED:
            Serial.println("Connected to AP!");
            digitalWrite(LED_BUILTIN, HIGH);
            break;
        case SYSTEM_EVENT_STA_DISCONNECTED:
            Serial.println("Disconnected. Reason: " + String(info.disconnected.reason));
            digitalWrite(LED_BUILTIN, LOW);
            WiFi.reconnect(); // Auto-reconnect
            break;
    }
}
void setup() {
    pinMode(LED_BUILTIN, OUTPUT);
    WiFi.onEvent(wifiEventHandler); // Register handler
    WiFi.begin("SSID", "PASSWORD");
}
  • Practical Tip: Use a state machine to manage complex workflows (e.g., retry failed connections with exponential backoff).

Handling Events in ESP-IDF🔗

For low-level control, ESP-IDFZigbee Over-the-Air (OTA) Firmware Updates with ESP32 CoordinatorsZigbee Over-the-Air (OTA) Firmware Updates with ESP32 CoordinatorsSecure your IoT network with OTA firmware upgrades using an ESP32 coordinator. Our guide details firmware setup, packaging, security, and troubleshooting.’s event loop provides granular management.

Example: Registering an Event Handler

#include "esp_event.h"
#include "esp_wifi.h"
void wifi_event_handler(void* arg, esp_event_base_t base, int32_t id, void* data) {
    if (base == WIFI_EVENT && id == WIFI_EVENT_STA_DISCONNECTED) {
        esp_wifi_connect(); // Immediate reconnect attempt
    }
}
void app_main() {
    esp_event_loop_create_default();
    esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID, wifi_event_handler, NULL);
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    esp_wifi_init(&cfg);
    esp_wifi_set_mode(WIFI_MODE_STA);
    esp_wifi_start();
    esp_wifi_connect();
}

Practical Example: Handling Connection and Disconnection🔗

Let’s build a more practical example where we handle connection and disconnection events to retry connecting to the Wi-Fi networkConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies. automatically.

#include <WiFi.h>
void WiFiEventHandler(WiFiEvent_t event) {
    switch (event) {
        case SYSTEM_EVENT_STA_CONNECTED:
            Serial.println("Connected to Wi-Fi!");
            break;
        case SYSTEM_EVENT_STA_DISCONNECTED:
            Serial.println("Disconnected from Wi-Fi. Reconnecting...");
            WiFi.reconnect(); // Attempt to reconnect
            break;
        case SYSTEM_EVENT_STA_GOT_IP:
            Serial.println("Obtained IP address!");
            break;
        default:
            break;
    }
}
void setup() {
    Serial.begin(115200);
    WiFi.onEvent(WiFiEventHandler);
    WiFi.begin("YourSSID", "YourPassword");
}
void loop() {
    // Your main code here
}

Advanced Event Management: Retries and Fallback Mechanisms🔗

For more robust applications, you can implement retries and fallback mechanisms. For example, if the ESP32 fails to reconnect after several attempts, it could switch to a backup Wi-Fi networkConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies. or enter a low-power mode.

Example:

#include <WiFi.h>
int retryCount = 0;
const int maxRetries = 5;
void WiFiEventHandler(WiFiEvent_t event) {
    switch (event) {
        case SYSTEM_EVENT_STA_CONNECTED:
            Serial.println("Connected to Wi-Fi!");
            retryCount = 0; // Reset retry count
            break;
        case SYSTEM_EVENT_STA_DISCONNECTED:
            Serial.println("Disconnected from Wi-Fi.");
            if (retryCount < maxRetries) {
                Serial.println("Reconnecting...");
                WiFi.reconnect();
                retryCount++;
            } else {
                Serial.println("Max retries reached. Entering fallback mode.");
                // Implement fallback logic here
            }
            break;
        case SYSTEM_EVENT_STA_GOT_IP:
            Serial.println("Obtained IP address!");
            break;
        default:
            break;
    }
}
void setup() {
    Serial.begin(115200);
    WiFi.onEvent(WiFiEventHandler);
    WiFi.begin("YourSSID", "YourPassword");
}
void loop() {
    // Your main code here
}

Common Use Cases and Solutions🔗

Automatic Reconnection

Problem: Intermittent Wi-FiArquitetura ESP32: SoC dual-core, subsistemas RF integradosArquitetura ESP32: SoC dual-core, subsistemas RF integradosDiscover the ESP32’s dual-core prowess and integrated RF subsystems for efficient, innovative IoT applications—from smart homes to industrial sensors. drops in industrial environments.

Solution:

void handleDisconnect() {
    static uint8_t retryCount = 0;
    if (retryCount < 5) {
        delay(1000 * retryCount); // Exponential backoff: 0s, 1s, 2s...
        WiFi.reconnect();
        retryCount++;
    } else {
        ESP.restart(); // Last resort
    }
}

Power Management

Problem: Battery-powered sensor needs sleep modeSIM7000G Module with ESP32: Configuring LTE-M and GNSSSIM7000G Module with ESP32: Configuring LTE-M and GNSSMaster ESP32 integration with SIM7000G for reliable LTE-M connectivity and precise GPS tracking, featuring hardware setup, AT commands, and power tips. when idle.

Solution:

case SYSTEM_EVENT_STA_GOT_IP:
    // Start data transmission
    sendSensorData();
    // Schedule deep sleep after task completion
    esp_deep_sleep(60 * 1000000); // Sleep 60 seconds
    break;

User Feedback

Problem: Users can’t tell if the device is connected.

Solution:

  • Blink LED rapidly during connection attempts.
  • Publish status to cloud:
if (event == SYSTEM_EVENT_STA_DISCONNECTED) {
    mqttClient.publish("device/status", "offline");
}

Debugging and Troubleshooting Wi-Fi Events🔗

Debugging Wi-Fi events is critical in a dynamic network environment where issues like interferenceZigbee Network Diagnostics: Resolving Packet Loss and InterferenceZigbee Network Diagnostics: Resolving Packet Loss and InterferenceDiscover effective methods to diagnose and resolve packet loss and interference in Zigbee networks using ESP32, ensuring reliable IoT connectivity. or unstable signals can occur. Here are some methods to improve your debugging strategy:

1. Serial Logging: Print detailed messages that include event types and error codes, which can provide clues during disconnections.

2. Error Codes: Familiarize yourself with the ESP32’sCombining Wi-Fi with Deep Sleep for Low-Power ApplicationsCombining Wi-Fi with Deep Sleep for Low-Power ApplicationsLearn how to integrate Wi-Fi and deep sleep on ESP32 to maximize battery life in IoT devices. This guide offers practical tips and step-by-step instructions. error codes, as they help pinpoint specific issues like authentication failures or network timeouts.

3. Event Filtering: If your project handles multiple events, filter unnecessary logs when troubleshootingConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies. to focus on the problematic behaviors.

Best Practices for Event Management🔗

1. Debounce Events

Avoid spamming reconnectionConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies. attempts:

unsigned long lastDisconnectTime = 0;
if (millis() - lastDisconnectTime > 5000) { // 5-second cooldown
  handleDisconnect();
}

2. Centralize Event Logging

Log events to SPIFFSCreating a Wi-Fi Configuration Web Panel for ESP32Creating a Wi-Fi Configuration Web Panel for ESP32Discover how to create a secure ESP32 Wi-Fi configuration web panel for dynamic IoT deployments. Enjoy easy network setups and improved device management. or a circular buffer for post-mortem analysis.

3. Use FreeRTOS Queues

Decouple event handling from critical tasks:

QueueHandle_t wifiQueue = xQueueCreate(10, sizeof(WiFiEvent_t));
xQueueSend(wifiQueue, &event, portMAX_DELAY); // Send event to queue

4. Handle DHCP Timeouts

If SYSTEM_EVENT_STA_GOT_IP isn’t triggered, force a renew:

wifi_sta_dhcpc_stop();
wifi_sta_dhcpc_start();

Conclusion🔗

Mastering Wi-Fi events transforms your ESP32Setting Up ESP32 as a Wi-Fi Access PointSetting Up ESP32 as a Wi-Fi Access PointMaster ESP32 AP configuration with our step-by-step guide. Set up a secure, local IoT network using practical code examples and optimization tips. from a fragile prototype to a production-ready IoTSigfox Message Encoding: Packing Sensor Data into 12-byte PayloadsSigfox Message Encoding: Packing Sensor Data into 12-byte PayloadsLearn efficient data encoding techniques for Sigfox's constrained 12-byte payloads. Discover bitwise operations, structured encoding & CBOR strategies. device. By reacting to disconnections, optimizing power, and providing user feedback, you ensure resilienceConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies. in unpredictable environments.

Wi-Fi event management on the ESP32 enables you to build smarter, more responsive IoT solutionsConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies.. With a clear understanding of the events-from successful connections to unexpected disconnections-and by implementing robust event handlers, your projects become more resilient to real-world network challenges. The key takeaways include:

Arming yourself with these insights enhances the reliability and performance of your IoT devicesConnecting ESP32 to Cloud Services via Wi-FiConnecting ESP32 to Cloud Services via Wi-FiDiscover how to connect your ESP32 to AWS, Azure, and Google Cloud using secure Wi-Fi. This guide covers setup, error handling, and low power strategies., ensuring they function efficiently even in unpredictable wireless environments.

Author: Marcelo V. Souza - Engenheiro de Sistemas e Entusiasta em IoT e Desenvolvimento de Software, com foco em inovação tecnológica.

References🔗

Share article

Related Articles