ESP32 WiFi Library – WiFi.onEvent

Home / References / ESP32 Library / WiFi API / Station

Description

The onEvent method in the ESP32 WiFi Library allows you to register a callback function that will be invoked when specific WiFi events occur. This method is useful for handling various WiFi-related events, such as connection status changes, IP address assignment, and more.


Syntax and Usage

The onEvent method can be used in multiple ways, depending on the type of callback function you want to register. Below are the different syntax options:

Callback with event ID only:

typedef void (*WiFiEventCb)(arduino_event_id_t); wifi_event_id_t onEvent(WiFiEventCb, arduino_event_id_t = ARDUINO_EVENT_MAX);

This form of the callback function takes only the event ID as an argument.

Callback with event ID and event info:

typedef struct{ arduino_event_id_t event_id; arduino_event_info_t event_info; } arduino_event_t; typedef void (*WiFiEventSysCb)(arduino_event_t *); wifi_event_id_t onEvent(WiFiEventSysCb, arduino_event_id_t = ARDUINO_EVENT_MAX);

This form of the callback function takes both the event ID and additional event information.

Callback using 

std::function:typedef std::function WiFiEventFuncCb; wifi_event_id_t onEvent(WiFiEventFuncCb, arduino_event_id_t = ARDUINO_EVENT_MAX);

This form allows you to use a more flexible callback function with std::function.

For practical applications and examples of this method, please consult the “Example Code” section on this page. This section provides comprehensive guidance to help you better understand and apply the method effectively.


Argument(s)

  • callback function: The function to be called when a WiFi event occurs. The type of callback function depends on the syntax used.
  • arduino_event_id_t: Optional. Specifies the specific event type for which the callback should be invoked. If not provided, the callback will be invoked for all WiFi events.

Return Value

The onEvent method returns a wifi_event_id_t value, which is the ID of the registered event callback.


Important:

Event callback functions are executed on a separate thread (a FreeRTOS task), distinct from the main application thread responsible for running setup() and loop(). Consequently, these callbacks must be designed to be thread-safe. This means they should avoid directly accessing shared or global variables without implementing proper locking mechanisms and should only invoke other functions that are also guaranteed to be thread-safe.

While certain core operations, such as Serial.print(), are thread-safe, many others do not share this property. Notably, WiFi.onEvent() and WiFi.removeEvent() are not thread-safe and thus should never be called from within a callback function to prevent potential data corruption or unexpected behavior. Ensuring thread safety is crucial for maintaining the integrity and stability of your application.


Example Codes

Example 1: Basic Event Callback

This code demonstrates how to use the ESP32 WiFi Library’s onEvent() method to monitor and handle WiFi events. By registering a callback function, the code prints the event ID whenever a WiFi event occurs, such as connecting to a network or losing connection.

To use this code, replace "your-ssid" and "your-password" with your actual WiFi credentials. Upload the code to your ESP32, and open the Serial Monitor to view the event IDs as they are triggered during WiFi operations.

/*
 * Author: Avant Maker
 * Date (MM-DD-YY): 02-06-25
 * Version: 1.0
 * Description: This example demonstrates how to use ESP32 WiFi.onEvent 
 * method and register a simple callback function that prints the 
 * event ID when a WiFi event occurs.
 *
 * License: MIT 
 * 
 * Code Source: This example code is sourced from the Comprehensive Guide
 * to the ESP32 Arduino Core Library, accessible on AvantMaker.com. 
 * For additional code examples and in-depth documentation related to 
 * the ESP32 Arduino Core Library, please visit:
 *
 * https://avantmaker.com/references/esp32-arduino-core-index/
 *
 * AvantMaker.com, your premier destination for all things DIY, AI, IoT, 
 * Smart Home, and STEM projects. We are dedicated to empowering makers,
 * learners, and enthusiasts with the resources they need to bring their 
 * innovative ideas to life.
 */

#include <WiFi.h>

void WiFiEvent(arduino_event_id_t event) {
    Serial.printf("WiFi event: %d\n", event);
}

void setup() {
    Serial.begin(115200);
    WiFi.onEvent(WiFiEvent);
    WiFi.begin("your-ssid", "your-password");
}

void loop() {
    // Your main loop code here
}

Example 2: Callback with Event Info

This code demonstrates how to use the ESP32 WiFi Library’s onEvent() method to register a callback function. The callback function, named WiFiEvent, is triggered whenever a WiFi-related event occurs. It receives an event object containing the event ID and additional event-specific information. For example, when the device connects to a WiFi network and obtains an IP address (event ID ARDUINO_EVENT_WIFI_STA_GOT_IP), the function extracts and prints the assigned IP address using the event’s data.

To use this code, replace “your-ssid” and “your-password” with your WiFi network credentials. Upload the code to your ESP32 board, open the Serial Monitor, and observe the event details and assigned IP address displayed during the connection process. The WiFiEvent function will handle various WiFi events, but in this example, it specifically processes the event where the ESP32 gets an IP address after connecting to the network.

/*
 * Author: Avant Maker
 * Date (MM-DD-YY): 02-06-25
 * Version: 1.0
 * Description: This example demonstrates how to use ESP32 WiFi.onEvent 
 * method and register a callback function that receives both the 
 * event ID and additional event information.
 *
 * License: MIT 
 * 
 * Code Source: This example code is sourced from the Comprehensive Guide
 * to the ESP32 Arduino Core Library, accessible on AvantMaker.com. 
 * For additional code examples and in-depth documentation related to 
 * the ESP32 Arduino Core Library, please visit:
 *
 * https://avantmaker.com/references/esp32-arduino-core-index/
 *
 * AvantMaker.com, your premier destination for all things DIY, AI, IoT, 
 * Smart Home, and STEM projects. We are dedicated to empowering makers,
 * learners, and enthusiasts with the resources they need to bring their 
 * innovative ideas to life.
 */

#include <WiFi.h>

void WiFiEvent(arduino_event_t *event) {
    Serial.printf("WiFi event: %d\n", event->event_id);
    if (event->event_id == ARDUINO_EVENT_WIFI_STA_GOT_IP) {
        Serial.print("IP address: ");
        Serial.println(IPAddress(event->event_info.got_ip.ip_info.ip.addr));
    }
}

void setup() {
    Serial.begin(115200);
    WiFi.onEvent(WiFiEvent);
    WiFi.begin("your-ssid", "your-password");
}

void loop() {
    // Your main loop code here
}

Example 3: Handle WiFi-Related Events

This code demonstrates how to use the ESP32 WiFi Library’s onEvent() method to monitor and respond to various WiFi events, such as connection status changes, IP assignment, and disconnections. The WiFiEvent callback function uses a switch statement to provide human-readable messages for each event type, while WiFiGotIP and a lambda function handle specific scenarios like IP acquisition and disconnection reasons.

To use this code, replace "your-ssid" and "your-password" with your WiFi credentials. Upload the sketch to your ESP32 and open the Serial Monitor to observe real-time event updates. Note that event handlers run in a separate FreeRTOS thread, and the example includes both function-based and lambda-based event registration, with optional event removal via removeEvent().

For more detailed description of this example code, please check out the explanation following the code.

/*
 * Author: Avant Maker
 * Date (MM-DD-YY): 02-06-25
 * Version: 1.0
 * Description: This code demonstrates how to use the onEvent method
 * from the ESP32 WiFi Library to handle various WiFi-related events. 
 * It showcases the registration of multiple event callbacks to monitor 
 * and respond to different WiFi states and activities.
 * 
 * Code Source: ESP32 Arduino Library Example Code 
 * 
 * For more detailed explaination about 
 * this code please refer to the Comprehensive Guide
 * to the ESP32 Arduino Core Library, accessible on AvantMaker.com. 
 * For additional code examples and in-depth documentation related to 
 * the ESP32 Arduino Core Library, please visit:
 *
 * https://avantmaker.com/references/esp32-arduino-core-index/
 *
 * AvantMaker.com, your premier destination for all things DIY, AI, IoT, 
 * Smart Home, and STEM projects. We are dedicated to empowering makers,
 * learners, and enthusiasts with the resources they need to bring their 
 * innovative ideas to life.
 */

/*
* WiFi Events

0  ARDUINO_EVENT_WIFI_READY               < ESP32 WiFi ready
1  ARDUINO_EVENT_WIFI_SCAN_DONE                < ESP32 finish scanning AP
2  ARDUINO_EVENT_WIFI_STA_START                < ESP32 station start
3  ARDUINO_EVENT_WIFI_STA_STOP                 < ESP32 station stop
4  ARDUINO_EVENT_WIFI_STA_CONNECTED            < ESP32 station connected to AP
5  ARDUINO_EVENT_WIFI_STA_DISCONNECTED         < ESP32 station disconnected from AP
6  ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE      < the auth mode of AP connected by ESP32 station changed
7  ARDUINO_EVENT_WIFI_STA_GOT_IP               < ESP32 station got IP from connected AP
8  ARDUINO_EVENT_WIFI_STA_LOST_IP              < ESP32 station lost IP and the IP is reset to 0
9  ARDUINO_EVENT_WPS_ER_SUCCESS       < ESP32 station wps succeeds in enrollee mode
10 ARDUINO_EVENT_WPS_ER_FAILED        < ESP32 station wps fails in enrollee mode
11 ARDUINO_EVENT_WPS_ER_TIMEOUT       < ESP32 station wps timeout in enrollee mode
12 ARDUINO_EVENT_WPS_ER_PIN           < ESP32 station wps pin code in enrollee mode
13 ARDUINO_EVENT_WIFI_AP_START                 < ESP32 soft-AP start
14 ARDUINO_EVENT_WIFI_AP_STOP                  < ESP32 soft-AP stop
15 ARDUINO_EVENT_WIFI_AP_STACONNECTED          < a station connected to ESP32 soft-AP
16 ARDUINO_EVENT_WIFI_AP_STADISCONNECTED       < a station disconnected from ESP32 soft-AP
17 ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED         < ESP32 soft-AP assign an IP to a connected station
18 ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED        < Receive probe request packet in soft-AP interface
19 ARDUINO_EVENT_WIFI_AP_GOT_IP6               < ESP32 ap interface v6IP addr is preferred
19 ARDUINO_EVENT_WIFI_STA_GOT_IP6              < ESP32 station interface v6IP addr is preferred
20 ARDUINO_EVENT_ETH_START                < ESP32 ethernet start
21 ARDUINO_EVENT_ETH_STOP                 < ESP32 ethernet stop
22 ARDUINO_EVENT_ETH_CONNECTED            < ESP32 ethernet phy link up
23 ARDUINO_EVENT_ETH_DISCONNECTED         < ESP32 ethernet phy link down
24 ARDUINO_EVENT_ETH_GOT_IP               < ESP32 ethernet got IP from connected AP
19 ARDUINO_EVENT_ETH_GOT_IP6              < ESP32 ethernet interface v6IP addr is preferred
25 ARDUINO_EVENT_MAX
*/

#include <WiFi.h>

const char *ssid = "your-ssid";
const char *password = "your-password";

// WARNING: This function is called from a separate FreeRTOS task (thread)!
void WiFiEvent(WiFiEvent_t event) {
  Serial.printf("[WiFi-event] event: %d\n", event);

  switch (event) {
    case ARDUINO_EVENT_WIFI_READY:               Serial.println("WiFi interface ready"); break;
    case ARDUINO_EVENT_WIFI_SCAN_DONE:           Serial.println("Completed scan for access points"); break;
    case ARDUINO_EVENT_WIFI_STA_START:           Serial.println("WiFi client started"); break;
    case ARDUINO_EVENT_WIFI_STA_STOP:            Serial.println("WiFi clients stopped"); break;
    case ARDUINO_EVENT_WIFI_STA_CONNECTED:       Serial.println("Connected to access point"); break;
    case ARDUINO_EVENT_WIFI_STA_DISCONNECTED:    Serial.println("Disconnected from WiFi access point"); break;
    case ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE: Serial.println("Authentication mode of access point has changed"); break;
    case ARDUINO_EVENT_WIFI_STA_GOT_IP:
      Serial.print("Obtained IP address: ");
      Serial.println(WiFi.localIP());
      break;
    case ARDUINO_EVENT_WIFI_STA_LOST_IP:        Serial.println("Lost IP address and IP address is reset to 0"); break;
    case ARDUINO_EVENT_WPS_ER_SUCCESS:          Serial.println("WiFi Protected Setup (WPS): succeeded in enrollee mode"); break;
    case ARDUINO_EVENT_WPS_ER_FAILED:           Serial.println("WiFi Protected Setup (WPS): failed in enrollee mode"); break;
    case ARDUINO_EVENT_WPS_ER_TIMEOUT:          Serial.println("WiFi Protected Setup (WPS): timeout in enrollee mode"); break;
    case ARDUINO_EVENT_WPS_ER_PIN:              Serial.println("WiFi Protected Setup (WPS): pin code in enrollee mode"); break;
    case ARDUINO_EVENT_WIFI_AP_START:           Serial.println("WiFi access point started"); break;
    case ARDUINO_EVENT_WIFI_AP_STOP:            Serial.println("WiFi access point  stopped"); break;
    case ARDUINO_EVENT_WIFI_AP_STACONNECTED:    Serial.println("Client connected"); break;
    case ARDUINO_EVENT_WIFI_AP_STADISCONNECTED: Serial.println("Client disconnected"); break;
    case ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED:   Serial.println("Assigned IP address to client"); break;
    case ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED:  Serial.println("Received probe request"); break;
    case ARDUINO_EVENT_WIFI_AP_GOT_IP6:         Serial.println("AP IPv6 is preferred"); break;
    case ARDUINO_EVENT_WIFI_STA_GOT_IP6:        Serial.println("STA IPv6 is preferred"); break;
    case ARDUINO_EVENT_ETH_GOT_IP6:             Serial.println("Ethernet IPv6 is preferred"); break;
    case ARDUINO_EVENT_ETH_START:               Serial.println("Ethernet started"); break;
    case ARDUINO_EVENT_ETH_STOP:                Serial.println("Ethernet stopped"); break;
    case ARDUINO_EVENT_ETH_CONNECTED:           Serial.println("Ethernet connected"); break;
    case ARDUINO_EVENT_ETH_DISCONNECTED:        Serial.println("Ethernet disconnected"); break;
    case ARDUINO_EVENT_ETH_GOT_IP:              Serial.println("Obtained IP address"); break;
    default:                                    break;
  }
}

// WARNING: This function is called from a separate FreeRTOS task (thread)!
void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info) {
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(IPAddress(info.got_ip.ip_info.ip.addr));
}

void setup() {
  Serial.begin(115200);

  // delete old config
  WiFi.disconnect(true);

  delay(1000);

  // Examples of different ways to register wifi events;
  // these handlers will be called from another thread.
  WiFi.onEvent(WiFiEvent);
  WiFi.onEvent(WiFiGotIP, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP);
  WiFiEventId_t eventID = WiFi.onEvent(
    [](WiFiEvent_t event, WiFiEventInfo_t info) {
      Serial.print("WiFi lost connection. Reason: ");
      Serial.println(info.wifi_sta_disconnected.reason);
    },
    WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED
  );

  // Remove WiFi event
  Serial.print("WiFi Event ID: ");
  Serial.println(eventID);
  // WiFi.removeEvent(eventID);

  WiFi.begin(ssid, password);

  Serial.println();
  Serial.println();
  Serial.println("Wait for WiFi... ");
}

void loop() {
  delay(1000);
}

Description of the Code

This example showcases the registration of multiple event callbacks to monitor and respond to different WiFi states and activities.

  • WiFi Event Handling Function (WiFiEvent)
    This function is called whenever a WiFi event occurs. It uses a switch statement to handle different events and logs descriptive messages to the Serial Monitor.
  • Specific Event Callback (WiFiGotIP)
    This function is registered to handle the ARDUINO_EVENT_WIFI_STA_GOT_IP event specifically. It prints a message indicating that the ESP32 has connected to a WiFi network and displays the assigned IP address.
  • Lambda Function for Disconnection Events
    A lambda function is registered to handle the ARDUINO_EVENT_WIFI_STA_DISCONNECTED event. It prints the reason for the disconnection, providing detailed insight into why the WiFi connection was lost.
  • Event Registration in setup()
    The WiFi.onEvent() method is used to register the WiFiEvent function for general WiFi events. Specific event handlers like WiFiGotIP and a lambda function are also registered. The code clears existing WiFi configurations and attempts to connect to a specified network.
  • Event ID Logging
    The ID of the registered event callback is logged to the Serial Monitor. This ID can be used to remove the callback later if needed.

AvantMaker Tutorial Suggestion

If you want to learn more about the ESP32’s WiFi capabilities, we’ve created a beginner-friendly guide that explains them in detail. Just click the link below, and you’ll be teleported to that page. It will clear up any confusion you may have while connecting your ESP32 to WiFi or setting it up as a WiFi access point (AP).

ESP32 Essential Guide – Network Section – WiFi Chapter

ESP32 Library Index

ESP32 Arduino Core Library


FAQ

Ready to experiment and explore more about ESP32? Visit our website’s All About ESP32 Resources Hub, packed with tutorials, guides, and tools to inspire your maker journey. Experiment, explore, and elevate your skills with everything you need to master this powerful microcontroller platform!

error: Content is protected !!