Useful Wi-Fi Library Functions for ESP32 (Arduino IDE)

This article provides a list of useful Wi-Fi Library functions for ESP32. We'll go through scanning Wi-Fi networks, connecting to a Wi-Fi network, getting Wi-Fi connection strength, checking connection status, reconnecting to the network if a connection is lost, Wi-Fi status, Wi-Fi modes, getting the ESP32 IP address, setting a fixed IP address, and more.

This is not a new situation. There are several examples of how to use the ESP32 to handle Wi-Fi. However, we thought it would be useful to compile a list of some of the most used and practical Wi-Fi Library functions for ESP32.

Table of Contents

Here is a list of topics that will be covered in this tutorial (click on the links to proceed to the corresponding section):

lilygo Official Store

Including the Wi-Fi Library

To use the ESP32 Wi-Fi functionalities, you first need to include the WiFi.h library in your code, as shown below:

#include <WiFi.h>

When you install the ESP32 add-on in your Arduino IDE, this library is “installed” automatically. Follow the next tutorial if you do not have the ESP32 installed:

To use the WiFi.h library and its functions, if you prefer to use VS Code + PaltformIO, you just need to start a new project with an ESP32 board.

ESP32 Wi-Fi Modes

The ESP32 board can function as a Wi-Fi Station, Point, or both. Use WiFi.mode() and provide the desired mode as an argument to set the Wi-Fi mode:

WiFi.mode(WIFI_STA)station mode: the ESP32 connects to an access point
WiFi.mode(WIFI_AP)access point mode: stations can connect to the ESP32
WiFi.mode(WIFI_AP_STA)access point and a station connected to another access point

Wi-Fi Station

When set up as a Wi-Fi station, the ESP32 may connect to other networks (such as your router). In this case, the router gives your ESP board a unique IP address. By using the ESP's unique IP address, you may interact with other devices (stations) that are also connected to the same network.

keyestudio Official Store

ESP32 Station Mode Router access point

We may request information from the internet using the ESP32 board, such as data from APIs (weather data, for example), send data to online platforms, use icons and photos from the internet, or include JavaScript libraries to construct web server pages.

Set the ESP32 as a Station and Connect to Wi-Fi Network

Go to “Connect to Wi-Fi Network” to learn how to set up the ESP32 as a station and connect it to a network.

When you don't have a network nearby but still want to connect to the ESP to control it, this may not be the ideal arrangement. Your ESP board must be set as an access point in this case.

Access Point

When your ESP32 board is set up as an access point, you may connect using any Wi-Fi-capable device without first connecting to your router. When you set the ESP32 as an access point, it creates its own Wi-Fi network to which nearby Wi-Fi devices (stations), such as your smartphone or computer, may connect. As a result, you do not need to be connected to a router to control it.

This might also be useful if you want to talk to several ESP32 devices without the need for a router.

TSCINBUNY Official Store

ESP32 Access Point Mode

The ESP32 is referred to as a soft-AP (soft Access Point) since it does not connect to a wired network like your router. This implies that trying to load libraries or use firmware via the internet will not work. It also doesn't work if you make HTTP requests to internet services to post sensor readings to the cloud or use internet services (like sending an email, for example).

Set the ESP32 as an Access Point

To set the ESP32 as an access point, set the Wi-Fi mode to access point:

WiFi.mode(WIFI_AP)

And then, use the softAP() method as follows:

WiFi.softAP(ssid, password);

The ssid a variable is the name you want to give the ESP32 access point and the password variable is the access point's password. Set it to NULL if you don't want to set a password.

You may also pass other optional parameters to the softAP() function. All of the parameters are listed below:

WiFi.softAP(const char* ssid, const char* password, int channel, int ssid_hidden, int max_connection)
  • ssid: name for the access point – maximum of 63 characters;
  • passwordminimum of 8 characters; set to NULL if you want the access point to be open;
  • channel: Wi-Fi channel number (1-13)
  • ssid_hidden: (0 = broadcast SSID, 1 = hide SSID)
  • max_connection: maximum simultaneous connected clients (1-4)

We have a complete tutorial explaining how to set up the ESP32 as an access point:

  • How to Set an ESP32 Access Point (AP) for Web Server (SOON)

Wi-Fi Station + Access Point

The ESP32 can be set as a Wi-Fi station and access point simultaneously. Set its mode to WIFI_AP_STA.

WiFi.mode(WIFI_AP_STA);

Scan Wi-Fi Networks

Within its Wi-Fi range, the ESP32 can scan for nearby Wi-Fi networks. Go to File > Examples > WiFi > WiFiScan in your Arduino IDE. This will load a sketch that scans Wi-Fi networks within your ESP32 board's range.

ESP32 Scan WiFi Networks

This might be useful to check whether the Wi-Fi network you're trying to connect to is within the range of your board or other apps. Your Wi-Fi project may not always work because it cannot connect to your router due to insufficient Wi-Fi strength.

Here’s an example:

/*
  Example from WiFi > WiFiScan
  Complete details at https://lededitpro.com/useful-wi-fi-library-functions-for-esp32-arduino-ide
*/

#include "WiFi.h"

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

  // Set WiFi to station mode and disconnect from an AP if it was previously connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  Serial.println("Setup done");
}

void loop() {
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0) {
      Serial.println("no networks found");
  } else {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i) {
      // Print SSID and RSSI for each network found
      Serial.print(i + 1);
      Serial.print(": ");
      Serial.print(WiFi.SSID(i));
      Serial.print(" (");
      Serial.print(WiFi.RSSI(i));
      Serial.print(")");
      Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN)?" ":"*");
      delay(10);
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
  delay(5000);
}

You may upload it to your board and check the RSSI (received signal strength indicator) as well as the networks that are accessible.

WiFi.scanNetworks() returns the number of networks found.

int n = WiFi.scanNetworks();

After the scanning, you can access the parameters of each network.

WiFi.SSID() prints the SSID for a specific network:

Serial.print(WiFi.SSID(i));

WiFi.RSSI() returns the network's RSSI. RSSI is an acronym that stands for Received Signal Strength Indicator. The power level that an RF client device is receiving from an access point or router is estimated.

Serial.print(WiFi.RSSI(i));

WiFi.encryptionType() finally returns the network encryption type. In the case of open networks, that specific example puts a *. Although it doesn't simply return open networks, the function may also return one of the following options:

  • WIFI_AUTH_OPEN
  • WIFI_AUTH_WEP
  • WIFI_AUTH_WPA_PSK
  • WIFI_AUTH_WPA2_PSK
  • WIFI_AUTH_WPA_WPA2_PSK
  • WIFI_AUTH_WPA2_ENTERPRISE
ESP32 Scan WiFi Networks Example Serial Monitor

Connect to a Wi-Fi Network

You need to know the SSID and password of a specific Wi-Fi network to connect the ESP32 to it. Additionally, that network must be accessible through the ESP32 Wi-Fi range (you can check this by scanning Wi-Fi networks using the previous example).

To connect the ESP32 to a Wi-Fi network, use the initWiFi() function.

void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

The ssid and password variables in the work variables hold the SSID and password of the network to which you want to connect.

// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Then, you simply need to call the initWiFi() function in your setup().

How does it work?

Let’s take a quick look at how this function works.

The Wi-Fi mode should be set first. When connected to another network (access point/hotspot), the ESP32 must be in station mode.

WiFi.mode(WIFI_STA);

Then, use WiFi.begin() to connect to a network. You must pass as arguments the network SSID and its password:

WiFi.begin(ssid, password);

Connecting to a Wi-Fi network might take some time, so we normally include a while loop that checks using WiFi.status() to see whether the connection has already been established. When the connection is established successfully, it returns WL_CONNECTED.

while (WiFi.status() != WL_CONNECTED) {

Get Wi-Fi Connection Status

WiFi.status() may be used to get the status of a Wi-Fi connection. This returns one of the following values, which correspond to the table's constants:

ValueConstantMeaning
0WL_IDLE_STATUStemporary status assigned when WiFi.begin() is called
1WL_NO_SSID_AVAIL when no SSID is available
2WL_SCAN_COMPLETEDscan networks are completed
3WL_CONNECTEDwhen connected to a WiFi network
4WL_CONNECT_FAILEDwhen the connection fails for all the attempts
5WL_CONNECTION_LOSTwhen the connection is lost
6WL_DISCONNECTEDwhen disconnected from a network

Get WiFi Connection Strength

After a WiFi connection, simply call WiFi.RSSI() to get the connection strength.

Here’s an example:

/*
  Complete details at https://lededitpro.com/useful-wi-fi-library-functions-for-esp32-arduino-ide
*/

#include <WiFi.h>

// Replace with your network credentials (STATION)
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

void setup() {
  Serial.begin(115200);
  initWiFi();
  Serial.print("RRSI: ");
  Serial.println(WiFi.RSSI());
}

void loop() {
  // put your main code here, to run repeatedly:
}

Insert your network credentials and upload the code.

The Serial Monitor should be open, and you should press the RST button on the ESP32 board. As soon as it is connected to your network, the RSSI (received signal strength indicator) will be printed.

Get ESP32 Wi-Fi Connection Strength

A lower absolute value means a stronger Wi-Fi connection.

Get ESP32 IP Address

When set up as a Wi-Fi station, the ESP32 may connect to other networks (such as your router). In this case, the router gives your ESP32 board a unique IP address. After establishing a connection with your network, you must call WiFi.localIP() to get your board's IP address.

Serial.println(WiFi.localIP());

Set a Static ESP32 IP Address

You may set an available IP preference of your choice for the ESP32 using WiFi.config() instead of receiving a randomly assigned IP address.

Define the following variables outside of the setup() and loop() procedures with your static IP address and associated gateway IP address. The following code assigns the IP address 192.168.1.184 to the gateway 192.168.1.1 by default.

// Set your Static IP address
IPAddress local_IP(192, 168, 1, 184);
// Set your Gateway IP address
IPAddress gateway(192, 168, 1, 1);

IPAddress subnet(255, 255, 0, 0);
IPAddress primaryDNS(8, 8, 8, 8);   // optional
IPAddress secondaryDNS(8, 8, 4, 4); // optional

Then, in the setup(), you need to call the WiFi.config() method to assign the configurations to your ESP32.

// Configures static IP address
if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
  Serial.println("STA Failed to configure");
}

The primaryDNS and secondaryDNS parameters are optional and you can remove them.

We recommend reading the following tutorial to learn how to set a static IP address:

Disconnect from Wi-Fi Network

To disconnect from a previously connected Wi-Fi network, use WiFi.disconnect():

WiFi.disconnect()
ESP32 Disconnect From Wi-Fi Network

Reconnect to Wi-Fi Network After Lost Connection

To reconnect to Wi-Fi after a connection is lost, you can use WiFi.reconnect() to try to reconnect to the previously connected access point:

WiFi.reconnect()

Or, you can call WiFi.disconnect() followed by WiFi.begin(ssid,password).

WiFi.disconnect();
WiFi.begin(ssid, password);

When the connection is lost, you may also try restarting the ESP32 using ESP.restart().

You may add something like the snippet below to your loop() that checks whether the board is connected once in a while.

unsigned long currentMillis = millis();
// if WiFi is down, try reconnecting
if ((WiFi.status() != WL_CONNECTED) && (currentMillis - previousMillis >=interval)) {
  Serial.print(millis());
  Serial.println("Reconnecting to WiFi...");
  WiFi.disconnect();
  WiFi.reconnect();
  previousMillis = currentMillis;
}

Don't forget to specify the interval, and previousMillis variables. The interval, in milliseconds (for example, 30 seconds), correspond to the period between each check:

unsigned long previousMillis = 0;
unsigned long interval = 30000;

Here’s a complete example.

/*
  LEDEdit PRO
  Complete project details at https://lededitpro.com/resolve-reconnect-esp32-to-wi-fi-network/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>

// Replace with your network credentials (STATION)
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

unsigned long previousMillis = 0;
unsigned long interval = 30000;

void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

void setup() {
  Serial.begin(115200);
  initWiFi();
  Serial.print("RSSI: ");
  Serial.println(WiFi.RSSI());
}

void loop() {
  unsigned long currentMillis = millis();
  // if WiFi is down, try reconnecting every CHECK_WIFI_TIME seconds
  if ((WiFi.status() != WL_CONNECTED) && (currentMillis - previousMillis >=interval)) {
    Serial.print(millis());
    Serial.println("Reconnecting to WiFi...");
    WiFi.disconnect();
    WiFi.reconnect();
    previousMillis = currentMillis;
  }
}

This example shows how to connect to a network and check every 30 seconds to see whether it is still connected. If not, it disconnects and tries to reconnect.

You can read our guide: [Resolve] Reconnect ESP32 to Wi-Fi Network After Lost Connection

As an alternative, you may use WiFi Events to detect when the connection was lost and then call a function to handle what happens next (see the part below this one for more information).

ESP32 Wi-Fi Events

The ESP32 can handle all the following Wi-Fi events (check the source code):

0ARDUINO_EVENT_WIFI_READYESP32 Wi-Fi ready
1ARDUINO_EVENT_WIFI_SCAN_DONEESP32 finishes scanning AP
2ARDUINO_EVENT_WIFI_STA_STARTESP32 station start
3ARDUINO_EVENT_WIFI_STA_STOPESP32 station stop
4ARDUINO_EVENT_WIFI_STA_CONNECTEDESP32 station connected to AP
5ARDUINO_EVENT_WIFI_STA_DISCONNECTEDESP32 station disconnected from AP
6ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGEthe auth mode of AP connected by ESP32 station changed
7ARDUINO_EVENT_WIFI_STA_GOT_IPESP32 station got IP from connected AP
8ARDUINO_EVENT_WIFI_STA_LOST_IPESP32 station lost IP and the IP is reset to 0
9ARDUINO_EVENT_WPS_ER_SUCCESSESP32 station wps succeeds in enrollee mode
10ARDUINO_EVENT_WPS_ER_FAILEDESP32 station wps fails in enrollee mode
11ARDUINO_EVENT_WPS_ER_TIMEOUTESP32 station wps timeout in enrollee mode
12ARDUINO_EVENT_WPS_ER_PINESP32 station wps pin code in enrollee mode
13ARDUINO_EVENT_WIFI_AP_STARTESP32 soft-AP start
14ARDUINO_EVENT_WIFI_AP_STOPESP32 soft-AP stop
15ARDUINO_EVENT_WIFI_AP_STACONNECTEDa station connected to ESP32 soft-AP
16ARDUINO_EVENT_WIFI_AP_STADISCONNECTEDa station disconnected from ESP32 soft-AP
17ARDUINO_EVENT_WIFI_AP_STAIPASSIGNEDESP32 soft-AP assign an IP to a connected station
18ARDUINO_EVENT_WIFI_AP_PROBEREQRECVEDReceive probe request packet in soft-AP interface
19ARDUINO_EVENT_WIFI_AP_GOT_IP6ESP32 access point v6IP addr is preferred
19ARDUINO_EVENT_WIFI_STA_GOT_IP6ESP32 station v6IP addr is preferred
19ARDUINO_EVENT_ETH_GOT_IP6Ethernet IPv6 is preferred
20ARDUINO_EVENT_ETH_STARTESP32 ethernet start
21ARDUINO_EVENT_ETH_STOPESP32 ethernet stop
22ARDUINO_EVENT_ETH_CONNECTEDESP32 ethernet phy link up
23ARDUINO_EVENT_ETH_DISCONNECTEDESP32 ethernet phy link down
24ARDUINO_EVENT_ETH_GOT_IPESP32 ethernet got IP from connected AP
25ARDUINO_EVENT_MAX

Go to File > Examples > WiFi > WiFiClientEvents for a complete example of how to use such events in your Arduino IDE.

/*   This sketch shows the WiFi event usage - Example from WiFi > WiFiClientEvents
     Complete details at https://lededitpro.com/useful-wi-fi-library-functions-for-esp32-arduino-ide/  */
/*
* 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     = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

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;
    }}

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
    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);
}

Wi-Fi Events eliminate the need to continually check the Wi-Fi status. The associated handling function is automatically called when a given event happens.

Reconnect to Wi-Fi Network After Lost Connection (Wi-Fi Events)

(Use the SYSTEM_EVENT_AP_STADISCONNECTED event). Wi-Fi events might be useful to detect when a connection has been lost and to try to reconnect right away. Here is some sample code:

/*
  LEDEdit PRO
  Complete project details at https://lededitpro.com/resolve-reconnect-esp32-to-wi-fi-network/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>
 
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

void WiFiStationConnected(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("Connected to AP successfully!");
}

void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void WiFiStationDisconnected(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("Disconnected from WiFi access point");
  Serial.print("WiFi lost connection. Reason: ");
  Serial.println(info.wifi_sta_disconnected.reason);
  Serial.println("Trying to Reconnect");
  WiFi.begin(ssid, password);
}

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

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

  delay(1000);

  WiFi.onEvent(WiFiStationConnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_CONNECTED);
  WiFi.onEvent(WiFiGotIP, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP);
  WiFi.onEvent(WiFiStationDisconnected, 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);
}
How did it work?

Three Wi-Fi events have been included in this example: the ESP32 connecting, getting an IP address, and disconnecting. ARDUINO_EVENT_WIFI_STA_CONNECTED, ARDUINO_EVENT_WIFI_STA_GOT_IP, ARDUINO_EVENT_WIFI_STA_DISCONNECTED

The WiFiStationConnected() function is invoked when the ESP32 station connects to the access point (ARDUINO_EVENT_WIFI_STA_CONNECTED event):

 WiFi.onEvent(WiFiStationConnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_CONNECTED);

The WiFiStationConnected() function simply prints that the ESP32 is successfully connected to an access point (such as your router). You may, however, alter the function to do any other task (for example, lighting an LED to indicate that it is successfully connected to the network).

void WiFiStationConnected(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("Connected to AP successfully!");
}

When the ESP32 gets its IP address, the WiFiGotIP() function runs.

 WiFi.onEvent(WiFiGotIP, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_GOT_IP);

That function simply prints the IP address on the Serial Monitor.

void WiFiGotIP(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

When the ESP32 loses the connection with the access point (ARDUINO_EVENT_WIFI_STA_DISCONNECTED), the WiFiStationDisconnected() function is called.

 WiFi.onEvent(WiFiStationDisconnected, WiFiEvent_t::ARDUINO_EVENT_WIFI_STA_DISCONNECTED);

This function prints a message stating that the connection has been lost and tries to reconnect:

void WiFiStationDisconnected(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("Disconnected from WiFi access point");
  Serial.print("WiFi lost connection. Reason: ");
  Serial.println(info.wifi_sta_disconnected.reason);
  Serial.println("Trying to Reconnect");
  WiFi.begin(ssid, password);
}

ESP32 WiFiMulti

You may register multiple networks (SSID/password combinations) using the ESP32 WiFiMulti. The Wi-Fi network with the strongest signal (RSSI) will be the one the ESP32 connects to. It will connect to the next network in the list if the current connection is lost. This requires the WiFiMulti.h library, which is already included with the ESP32 package and doesn't need to be installed.

To learn how to use WiFiMulti, read the following tutorial:

Change ESP32 Hostname

To set a custom hostname for your board, call WiFi.setHostname(YOUR_NEW_HOSTNAME); before WiFi.begin();

The default ESP32 hostname is espressif.

ESP32 default hostname f

There is a method provided by the WiFi.h library that allows you to set a custom hostname.

First, start by defining your new hostname. For example:

String hostname = "ESP32 Node Temperature";

Then, call the WiFi.setHostname() function before calling WiFi.begin(). You also need to call WiFi.config() as shown below:

WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE, INADDR_NONE);
WiFi.setHostname(hostname.c_str()); //define hostname

You can copy the complete example below:

/*
  LEDEdit PRO
  Complete project details at https://lededitpro.com/set-a-custom-hostname-for-esp32-using-arduino-ide/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>

// Replace with your network credentials (STATION)
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

String hostname = "ESP32 Node Temperature";

void initWiFi() {
  WiFi.mode(WIFI_STA);
  WiFi.config(INADDR_NONE, INADDR_NONE, INADDR_NONE, INADDR_NONE);
  WiFi.setHostname(hostname.c_str()); //define hostname
  //wifi_station_set_hostname( hostname.c_str() );
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

void setup() {
  Serial.begin(115200);
  initWiFi();
  Serial.print("RRSI: ");
  Serial.println(WiFi.RSSI());
}

void loop() {
  // put your main code here, to run repeatedly:
}

This previous snippet of code may be used in your projects to set a custom hostname for the ESP32.

Important: you may need to restart your router for the changes to take effect.

If you go to your router settings after that, you'll see the ESP32 with the custom hostname.

ESP32-Custom-Hostname

Conclusion

This article is a list of some of the most frequently used and useful Wi-Fi Library Functions for ESP32. Although there are many examples of how to use the ESP32 Wi-Fi capabilities, there is little documentation on how to use the Wi-Fi functions with the ESP32 using the Arduino IDE. As a result, we decided to put together this tutorial to help you use ESP32 Wi-Fi-related functions in your projects.

If you have other suggestions, you can share them in the comments section.

If you like ESP32, you may also like:

We hope you find this tutorial useful. Thanks for reading.

Oh hi there It’s nice to meet you.

Sign up to receive awesome content in your inbox, every month.

We don’t spam! Read our privacy policy for more info.

Leave a Reply

Your email address will not be published. Required fields are marked *

Developing IoT Projects with ESP32

Automate your home or business with inexpensive Wi-Fi devices