Skip to content

uPesy now ships to the entire European Union

Livraison à partir de seulement 2.50€ !

Contents Menu Expand Light mode Dark mode Auto light/dark mode

How to connect to a WiFi network with the ESP32

(Updated at 01/20/2023)

The built-in WiFi.h library will allow us to use the WiFi features of the ESP32 board easily.

The ESP32 has 2 WiFi modes:

  • STATION ( WIFI_STA ) : The Station mode (STA) is used to connect the ESP32 module to a WiFi access point. The ESP32 behaves like a computer that is connected to our router. If the router is connected to the Internet, then the ESP32 can access the Internet. The ESP32 can behave as a client: make requests to other devices connected to the network, or as a server: other devices connected to the network will send requests to the ESP32. In both cases, the ESP32 can access the Internet.

  • AP (Access Point) (WIFI_AP ): In Access Point mode, the ESP32 behaves like a WiFi network (a bit like a router): other devices can connect to it. In this mode, the ESP32 is not connected to any other network and is therefore not connected to the Internet. This mode is more computationally and energy-intensive (the ESP32 board will heat up) since the ESP32 has to simulate a full WiFi router (Soft AP). The latency and the bandwidth will be less efficient than in a classic router.

Note

The ESP32 is, by default in STATION mode.

For mode selection :

  • In general, we use the STATION mode. We can access the Internet to retrieve information from an API, have a home automation server with sensors …

  • The AP mode is usually used temporarily to enter the credentials of the WiFi network (SSID and password). It can also be used to have a separate network from your home network and not be connected to the Internet.

Connecting to a Wi-Fi Access Point

The code to connect to his AP is as follows:

#include <WiFi.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

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

    WiFi.mode(WIFI_STA); //Optional
    WiFi.begin(ssid, password);
    Serial.println("\nConnecting");

    while(WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(100);
    }

    Serial.println("\nConnected to the WiFi network");
    Serial.print("Local ESP32 IP: ");
    Serial.println(WiFi.localIP());
}

void loop(){}

Important

You need to change "yourNetworkName" to the name of your WiFi network and "yourNetworkPassword" to your network password.

Terminal output

Connecting
................
Connected to the WiFi network
Local ESP32 IP: 192.168.43.129

Tip

An easy way to have a WiFi access point to test the code is by sharing a WiFi connection from your smartphone.

The code functions as follows:

  • We must include the WiFi.h library.

  • Then we enter the name of the network and its password.

  • We put the ESP32 in STATION mode with the function WiFi.mode(WIFI_STA)

  • The ESP32 tries to connect to the Wi-Fi network using the function WiFi.begin(ssid, password)

  • The connection is not instantaneous! It is therefore necessary to regularly check the connection status: as long as the ESP32 is not connected to the network, we will remain blocked inside the while loop. We add a slight delay to avoid constantly checking the status.

  • Once the connection has been established, the local IP address of the ESP32 on this network will be displayed.

If it is an open network (without a password), then the code becomes simpler:

#include <WiFi.h>

const char* ssid = "yourNetworkName";

void setup(){
Serial.begin(115200);
delay(1000);
WiFi.begin(ssid);
Serial.println("\nConnecting");

while(WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(100);
}

Serial.println("\nConnected to the WiFi network");
Serial.print("Local ESP32 IP: ");
Serial.println(WiFi.localIP());
}

void loop(){}

Note

Storing logins and passwords in clear text in the code is a bad practice. However, doing so simplify tutorials.

Get WiFi network information

You can get information about the network once you are connected to it:

  • WiFi signal strength (RSSI) with the WiFi.RSSI() function

  • The MAC address of the WiFi network with WiFi.BSSIDstr() or WiFi.macAddress()

  • The local IP address of the ESP32 assigned by the DHCP server of the WiFi network with WiFi.localIP()

  • The local IP address of the WiFi network (gateway) with WiFi.gatewayIP() (usually 192.168.0.1)

  • The subnet mask with WiFi.subnetMask() (usually 255.255.255.0)

The code below displays all this information:

#include <WiFi.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

void get_network_info(){
    if(WiFi.status() == WL_CONNECTED) {
        Serial.print("[*] Network information for ");
        Serial.println(ssid);

        Serial.println("[+] BSSID : " + WiFi.BSSIDstr());
        Serial.print("[+] Gateway IP : ");
        Serial.println(WiFi.gatewayIP());
        Serial.print("[+] Subnet Mask : ");
        Serial.println(WiFi.subnetMask());
        Serial.println((String)"[+] RSSI : " + WiFi.RSSI() + " dB");
        Serial.print("[+] ESP32 IP : ");
        Serial.println(WiFi.localIP());
    }
}

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

    WiFi.begin(ssid, password);
    Serial.println("\nConnecting");

    while(WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(100);
    }

    Serial.println("\nConnected to the WiFi network");
    get_network_info();
}

void loop(){}

Terminal output

Connecting
..............
Connected to the WiFi network
[*] Network information for HUAWEI_**
[+] BSSID : F0:43:47:32:1F:4D
[+] Gateway IP : 192.168.43.1
[+] Subnet Mask : 255.255.255.0
[+] RSSI : -25 dB
[+] ESP32 IP : 192.168.43.129

Debug Wi-Fi connection issues

By monitoring the connection status

We can know the status of the WiFi connection with the function WiFi.status() . This function returns an integer according to the current status of the connection.

The possible statuses are :

  • WL_IDLE_STATUS : This is the default status before trying to connect to a network.

  • WL_SCAN_COMPLETED : The WiFi network scan is completed.

  • WL_NO_SSID_AVAIL : The ESP32 cannot find the name of the WiFi network. Either the network is too far from the ESP32, or the name (SSID) of the network is incorrect.

  • WL_CONNECT_FAILED : The ESP32 cannot connect to the designated WiFi network.

  • WL_CONNECTION_LOST : The WiFi connection to the network is lost. If this error occurs repeatedly, it may be a power problem with the ESP32.

  • WL_CONNECTED : The ESP32 is connected to the WiFi network.

  • WL_DISCONNECTED : The ESP32 is disconnected from the WiFi network.

Code that displays the status of the WiFi connection

#include <WiFi.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

String get_wifi_status(int status){
    switch(status){
        case WL_IDLE_STATUS:
        return "WL_IDLE_STATUS";
        case WL_SCAN_COMPLETED:
        return "WL_SCAN_COMPLETED";
        case WL_NO_SSID_AVAIL:
        return "WL_NO_SSID_AVAIL";
        case WL_CONNECT_FAILED:
        return "WL_CONNECT_FAILED";
        case WL_CONNECTION_LOST:
        return "WL_CONNECTION_LOST";
        case WL_CONNECTED:
        return "WL_CONNECTED";
        case WL_DISCONNECTED:
        return "WL_DISCONNECTED";
    }
}

void setup(){
    Serial.begin(115200);
    delay(1000);
    int status = WL_IDLE_STATUS;
    Serial.println("\nConnecting");
    Serial.println(get_wifi_status(status));
    WiFi.begin(ssid, password);
    while(status != WL_CONNECTED){
        delay(500);
        status = WiFi.status();
        Serial.println(get_wifi_status(status));
    }

    Serial.println("\nConnected to the WiFi network");
    Serial.print("Local ESP32 IP: ");
    Serial.println(WiFi.localIP());
}

void loop(){}

Examples of possible scenarios

Connecting
WL_IDLE_STATUS
WL_DISCONNECTED
WL_DISCONNECTED
WL_CONNECTED

Connected to the WiFi network
Local ESP32 IP: 192.168.43.129
Connecting
WL_IDLE_STATUS
WL_DISCONNECTED
WL_DISCONNECTED
WL_NO_SSID_AVAIL
WL_NO_SSID_AVAIL
WL_NO_SSID_AVAIL
WL_NO_SSID_WORK
Connecting
WL_IDLE_STATUS
WL_DISCONNECTED
WL_DISCONNECTED
WL_NO_SSID_AVAIL
WL_NO_SSID_AVAIL
WL_NO_SSID_AVAIL
WL_NO_SSID_WORK

By restarting the ESP32

Occasionally, the ESP32 may temporarily fail to connect to the WiFi for unknown or strange reasons. The best solution is to say that after n seconds, if the ESP32 still hasn’t connected to WiFi, we restart the ESP32. Just add a timeout and use the ESP.restart() function to restart the ESP32 from the code.

Here is an example that will restart the ESP32 after 10 seconds if it is still not connected to WiFi.

#include <WiFi.h>

#define CONNECTION_TIMEOUT 10

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

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

    WiFi.mode(WIFI_STA); //Optional
    WiFi.begin(ssid, password);
    Serial.println("\nConnecting");
    int timeout_counter = 0;

    while(WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(200);
        timeout_counter++;
        if(timeout_counter >= CONNECTION_TIMEOUT*5){
        ESP.restart();
        }
    }

    Serial.println("\nConnected to the WiFi network");
    Serial.print("Local ESP32 IP: ");
    Serial.println(WiFi.localIP());
}

void loop(){}

The ESP32 is reset after 10 seconds in case of connection failure from the code with the the``SW_CPU_RESET`` flag during the boot.

Connecting
.......................................................

ets Jun  8 2016 00:22:57

rst:0xc (SW_CPU_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1044
load:0x40078000,len:8896
load:0x40080400,len:5816
entry 0x400806ac

Connecting
.......
Connected to the WiFi network
Local ESP32 IP: 192.168.43.129

Change Wi-Fi channel

If the ESP32 has difficulty connecting to the WiFi depending on the period (or time slot), it may be related to the Wi-Fi channel chosen by your Acces Point. In fact, even if the Wi-Fi frequency is at 2.4GHz, the AP uses many subbands around 2.4GHz, called channels, to reduce the traffic. This makes it possible to have many different Wi-Fi routers in a very close space in buildings without them interfering with each other.

For France, there are 14 channels available. The available channels vary according to the country. In general, the channel is chosen automatically by the router (in auto ), depending on the other channels used by the AP around. Except that, in practice, the routers are always stuck on the last channels, 12, 13 and 14

One solution is to change the channel number used by the router to number 1, 6 or 11, for example. This change is done via the router’s administrator interface, usually on IP 192.168.0.1 .

If you use a lot of Wi-Fi-connected IoT objects, I recommend having a second Wi-Fi router to separate home use from IoT use. You shouldn’t have any more Wi-Fi connection issues by choosing channel 1 or 6 for the IoT sensor router and a channel between 11 and 14 for the other router.

Advance WiFi network stuffs for the ESP32

Assign a static IP address

The local IP address of the ESP32 has been assigned automatically by the router’s DHCP server. It is convenient to have an IP address automatically on the computer because we do not have to enter it manually. The disadvantage (or advantage, depending on the case) is that the IP address is dynamic: it can change. This can become annoying if, for example, as soon as the ESP32 is restarted (or the DHCP lease is expired), the IP address changes while a web server is running on the ESP32. We would have to find the IP of the ESP32 every time. We can overcome this problem by setting the IP address of the ESP32 on the network. To do this, use the WiFi.config(ip, dns, gateway, subnet) function.

The parameters to be filled in are :

  • IP : The IP address you wish to assign.

  • DNS : Service that links a URL to an IP. By default, we use the DNS server of the router: so we indicate the same address as the router (in general, 192.168.0.1).

  • GATEWAY : This is the IP address of the router (usually 192.168.0.1)

  • SUBNET : Subnet mask (usually 255.255.255.0)

Note

You need to know the router’s IP address: the easiest way is to use the code that displays the WiFi network information in the serial monitor.

In this example, using the WiFi connection sharing of a phone, the router IP address is 192.168.43.1. I choose to have the following static IP 192.168.43.42 for the ESP32.

Code to set the IP address of the ESP32

#include <WiFi.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

IPAddress ip(192, 168, 43, 42);
IPAddress dns(192, 168, 43, 1);
IPAddress gateway(192, 168, 43, 1);
IPAddress subnet(255, 255, 255, 0);

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

WiFi.config(ip, gateway, subnet, dns);
WiFi.begin(ssid, password);
Serial.println("\nConnecting");

while(WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(100);
}

Serial.println("\nConnected to the WiFi network");
Serial.print("[+] ESP32 IP : ");
Serial.println(WiFi.localIP());
}

void loop(){}

Warning

It is important to remember not to use an IP address already taken by another device on the network. You can also assign a fixed IP address linked to the MAC address directly from the router settings.

For information purposes, we can then ping the computer to the IP 192.168.43.42 to see if the new address has been taken into account:

Result of a ping in the Windows command prompt

Ping the ESP32 from the Windows terminal (cmd.exe)

Note

Suppose you have the error, ping: transmission failure. General failure , there is probably a software or firewall that disables the use of pings. This can be the case with VPN clients.

Change the MAC address

In some applications, it can be interesting to change the MAC address of the ESP32. We can change the MAC address with a few lines of code using the esp_wifi_set_mac() function.

Note

The MAC address change is temporary and does not replace the original one. You have to upload a new program to find the original MAC address.

#include <WiFi.h>
#include <esp_wifi.h>

uint8_t new_mac[] = {0x60, 0x8B, 0x0E, 0x01, 0x5A, 0x32};

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

    WiFi.mode(WIFI_STA);//Needed to change MAC adress
    Serial.print("[+] Current MAC Address:  ");
    Serial.println(WiFi.macAddress());

    esp_wifi_set_mac(ESP_IF_WIFI_STA, new_mac);

    Serial.print("[+] New MAC Address:  ");
    Serial.println(WiFi.macAddress());
}

void loop(){}

Serial terminal :

[+] Current MAC Address:  24:6F:28:BB:2E:E8
[+] New MAC Address:  60:8B:0E:01:5A:32

Code that connects to a Wi-Fi network with a modified MAC address

#include <WiFi.h>
#include <esp_wifi.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

uint8_t new_mac[] = {0x6C, 0x8D, 0xC1, 0x01, 0x5A, 0x32};

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

    WiFi.mode(WIFI_STA);//Needed to change MAC adress
    esp_wifi_set_mac(ESP_IF_WIFI_STA, new_mac);
    delay(1000);
    WiFi.begin(ssid, password);
    Serial.println("\nConnecting");

    while(WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(100);
    }

    Serial.println("\nConnected to the WiFi network");
    Serial.print("Local ESP32 IP: ");
    Serial.println(WiFi.localIP());
}

void loop(){}

A Wireshark capture shows that the address has been changed (here by an Apple MAC address):

wireshark capture changing mac adress esp32

Capture a network frame with Wireshark

Save energy

If you are using an ESP32 in a project that must necessarily use WiFi to work, it is a good idea to set the ESP32 to Deep Sleep mode in case of connection failure to minimize power consumption. This is similar to the ESP32 code that sleeps for 10 seconds between each attempt.

Code that allows putting the ESP32 in Deep Sleep between 2 attempts

#include <WiFi.h>
#include <esp_wifi.h>

//Time in seconds
#define CONNECTION_TIMEOUT 5
#define DEEP_SLEEP_DURATION 10

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

void setup(){
    Serial.begin(115200);
    WiFi.begin(ssid, password);
    Serial.println("\nConnecting");
    int timeout_counter = 0;

    while(WiFi.status() != WL_CONNECTED){
        Serial.print(".");
        delay(100);
        timeout_counter++;
            if(timeout_counter >= CONNECTION_TIMEOUT*10){
                Serial.println("\nCan't establish WiFi connexion");
                //Setup timer
                esp_sleep_enable_timer_wakeup(DEEP_SLEEP_DURATION * 1000000);
                //Start deep sleep
                esp_deep_sleep_start();
            }
    }
    Serial.println("\nConnected to the WiFi network");
    Serial.print("Local ESP32 IP: ");
    Serial.println(WiFi.localIP());
}

void loop(){}

Use WiFi events to have an optimized code

Until now, we used to poll the WiFi functions: the ESP32 remains blocked until it receives an event from the ESP32 WiFi driver. We were doing sequential programming. Here’s an example:

while(WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(100);
}

We regularly check if the ESP32 has successfully connected to the WiFi network. While waiting, we’re not doing anything (we could make calculations between 2 polls) and are stuck in the loop.

A more efficient way of doing this is to use event-driven programming. Indeed, events are generated when the WiFi changes state. The advantage is that we can execute code automatically depending on the event received. This is very similar to the interrupts that we use on the GPIO pins. A change of state of the pin generates an interrupt, which will execute a portion of high-priority code. Here a change of state of the WiFi generates an event that will also execute a portion of code.

The basic code for managing events is as follows:

#include <WiFi.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

void my_function(WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info){
    //Code
}

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

    WiFi.mode(WIFI_STA); //Optional
    WiFi.onEvent(my_function, WIFI_EVENT_ID);

    WiFi.begin(ssid, password);
}

void loop(){}

We use the function WiFi.onEvent(my_function, WIFI_EVENT_ID) to specify which function will be executed when the event WIFI_EVENT_ID is detected. WIFI_EVENT_ID must be replaced by the name or number of the event (see table below). The function my_function() must have the parameters WiFiEvent_t wifi_event , WiFiEventInfo_t wifi_info even if they are not used.

Warning

Depending on the version of the ESP32 port in Arduino code you have installed, the name of the events is different.

Liste des évènements Wi-Fi

Number

Event Name

Description

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

Wi-Fi Events List

Number

Event Name

Description

0

SYSTEM_EVENT_WIFI_READY

ESP32 WiFi ready

1

SYSTEM_EVENT_SCAN_DONE

ESP32 finish scanning AP

2

SYSTEM_EVENT_STA_START

ESP32 station start

3

SYSTEM_EVENT_STA_STOP

ESP32 station stop

4

SYSTEM_EVENT_STA_CONNECTED

ESP32 station connected to AP

5

SYSTEM_EVENT_STA_DISCONNECTED

ESP32 station disconnected from AP

6

SYSTEM_EVENT_STA_AUTHMODE_CHANGE

the auth mode of AP connected by ESP32 station changed

7

SYSTEM_EVENT_STA_GOT_IP

ESP32 station got IP from connected AP

8

SYSTEM_EVENT_STA_LOST_IP

ESP32 station lost IP and the IP is reset to 0

9

SYSTEM_EVENT_STA_WPS_ER_SUCCESS

ESP32 station wps succeeds in enrollee mode

10

SYSTEM_EVENT_STA_WPS_ER_FAILED

ESP32 station wps fails in enrollee mode

11

SYSTEM_EVENT_STA_WPS_ER_TIMEOUT

ESP32 station wps timeout in enrollee mode

12

SYSTEM_EVENT_STA_WPS_ER_PIN

ESP32 station wps pin code in enrollee mode

13

SYSTEM_EVENT_AP_START

ESP32 soft-AP start

14

SYSTEM_EVENT_AP_STOP

ESP32 soft-AP stop

15

SYSTEM_EVENT_AP_STACONNECTED

a station connected to ESP32 soft-AP

16

SYSTEM_EVENT_AP_STADISCONNECTED

a station disconnected from ESP32 soft-AP

17

SYSTEM_EVENT_AP_STAIPASSIGNED

ESP32 soft-AP assign an IP to a connected station

18

SYSTEM_EVENT_AP_PROBEREQRECVED

Receive probe request packet in soft-AP interface

19

SYSTEM_EVENT_GOT_IP6

ESP32 station or ap or ethernet interface v6IP addr is preferred

20

SYSTEM_EVENT_ETH_START

ESP32 ethernet start

21

SYSTEM_EVENT_ETH_STOP

ESP32 ethernet stop

22

SYSTEM_EVENT_ETH_CONNECTED

ESP32 ethernet phy link up

23

SYSTEM_EVENT_ETH_DISCONNECTED

ESP32 ethernet phy link down

24

SYSTEM_EVENT_ETH_GOT_IP

ESP32 ethernet got IP from connected AP

25

SYSTEM_EVENT_MAX

The following code does the same thing as the code at the very beginning to connect to a router, but this time with the use of events when connected to a network.

Code that allows connecting to a router with WiFi events

#include <WiFi.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

void connected_to_ap(WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info) {
  Serial.println("\nConnected to the WiFi network");
}

void got_ip_from_ap(WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info) {
  Serial.print("Local ESP32 IP: ");
  Serial.println(WiFi.localIP());
}

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

  WiFi.mode(WIFI_STA); //Optional
  WiFi.onEvent(connected_to_ap, ARDUINO_EVENT_WIFI_STA_CONNECTED);
  WiFi.onEvent(got_ip_from_ap, ARDUINO_EVENT_WIFI_STA_GOT_IP);

  WiFi.begin(ssid, password);
  Serial.println("\nConnecting");
}

void loop() {}

Console output:

Connecting
.............
Connected to the WiFi network
Local ESP32 IP: 192.168.43.167

You can remove the execution of the function linked to an event during the execution of the program with wifi.removeEvent(WIFI_EVENT_ID)

A practical use case of events is the possibility of automatically reconnecting the ESP32 in case of disconnection.

#include <WiFi.h>

const char* ssid = "yourNetworkName";
const char* password = "yourNetworkPassword";

void connected_to_ap(WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info) {
  Serial.println("[+] Connected to the WiFi network");
}

void disconnected_from_ap(WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info) {
  Serial.println("[-] Disconnected from the WiFi AP");
  WiFi.begin(ssid, password);
}

void got_ip_from_ap(WiFiEvent_t wifi_event, WiFiEventInfo_t wifi_info) {
  Serial.print("[+] Local ESP32 IP: ");
  Serial.println(WiFi.localIP());
}

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

  WiFi.mode(WIFI_STA); //Optional
  WiFi.onEvent(connected_to_ap, ARDUINO_EVENT_WIFI_STA_CONNECTED);
  WiFi.onEvent(got_ip_from_ap, ARDUINO_EVENT_WIFI_STA_GOT_IP);
  WiFi.onEvent(disconnected_from_ap, ARDUINO_EVENT_WIFI_STA_DISCONNECTED);

  WiFi.begin(ssid, password);
  Serial.println("\nConnecting");
}

void loop() {}

Console output:

Connecting
[-] Disconnected from the WiFi AP
[+] Connected to the WiFi network
[+] Local ESP32 IP: 192.168.43.167
[-] Disconnected from the WiFi AP
[-] Disconnected from the WiFi AP
[-] Disconnected from the WiFi AP
[-] Disconnected from the WiFi AP
[+] Connected to the WiFi network
Local ESP32 IP: 192.168.43.167

Application example: Wi-Fi Scan

Here is a concrete application that allows you to scan the WiFi networks around:

#include "WiFi.h"

String get_encryption_type(wifi_auth_mode_t encryptionType) {
    switch (encryptionType) {
        case (WIFI_AUTH_OPEN):
            return "Open";
        case (WIFI_AUTH_WEP):
            return "WEP";
        case (WIFI_AUTH_WPA_PSK):
            return "WPA_PSK";
        case (WIFI_AUTH_WPA2_PSK):
            return "WPA2_PSK";
        case (WIFI_AUTH_WPA_WPA2_PSK):
            return "WPA_WPA2_PSK";
        case (WIFI_AUTH_WPA2_ENTERPRISE):
            return "WPA2_ENTERPRISE";
    }
}

void setup(){
    Serial.begin(115200);
    WiFi.mode(WIFI_STA);
}

void loop() {
    Serial.println("uPesy WiFi Scan Demo");
    Serial.println("[*] Scanning WiFi network");

        // WiFi.scanNetworks will return the number of networks found
        int n = WiFi.scanNetworks();
        Serial.println("[*] Scan done");
        if (n == 0) {
            Serial.println("[-] No WiFi networks found");
        } else {
            Serial.println((String)"[+] " + n + " WiFi networks found\n");
            for (int i = 0; i < n; ++i) {
                // Print SSID, RSSI and WiFi Encryption for each network found
                Serial.print(i + 1);
                Serial.print(": ");
                Serial.print(WiFi.SSID(i));
                Serial.print(" (");
                Serial.print(WiFi.RSSI(i));
                Serial.print(" dB) [");
                Serial.print(get_encryption_type(WiFi.encryptionType(i)));
                Serial.println("]");
                delay(10);
            }
        }
        Serial.println("");

        // Wait a bit before scanning again
        delay(5000);
}
Scanning of surrounding wifi networks

ESP32 program that scans Wi-Fi surroundings router