ESP32 Useful Wi-Fi Library Functions (Arduino IDE)

This article is a compilation of useful Wi-Fi functions for the ESP32. We’ll cover the following topics: scan Wi-Fi networks, connect to a Wi-Fi network, get Wi-Fi connection strength, check connection status, reconnect to the network after connection is lost, Wi-Fi status, Wi-Fi modes, get the ESP32 IP address, set a fixed IP address and more.

This is not a novelty, there are plenty of examples on how to handle Wi-Fi with the ESP32. However, we thought it would be useful to compile some of the most used and practical Wi-Fi functions for the ESP32.

ESP32 Useful Wi-Fi Library Functions Arduino IDE

Table of Contents

Here’s a list of what will be covered in this tutorial (you can click on the links to go to the corresponding section):

Including the Wi-Fi Library

The first thing you need to do to use the ESP32 Wi-Fi functionalities is to include the WiFi.h library in your code, as follows:

#include <WiFi.h>

This library is automatically “installed” when you install the ESP32 add-on in your Arduino IDE. If you don’t have the ESP32 installed, you can follow the next tutorial:

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

ESP32 Wi-Fi Modes

The ESP32 board can act as Wi-Fi Station, Access Point or both. To set the Wi-Fi mode, use WiFi.mode() and set the desired mode as argument:

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_STA_AP)access point and a station connected to another access point

Wi-Fi Station

When the ESP32 is set as a Wi-Fi station, it can connect to other networks (like your router). In this scenario, the router assigns a unique IP address to your ESP board. You can communicate with the ESP using other devices (stations) that are also connected to the same network by referring to the ESP unique IP address.

ESP32 Station Mode Router access point

The router is connected to the internet, so we can request information from the internet using the ESP32 board like data from APIs (weather data, for example), publish data to online platforms, use icons and images from the internet or include JavaScript libraries to build 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 the ESP32 as station and connect it to a network.

In some cases, this might not be the best configuration – when you don’t have a network nearby and want you still want to connect to the ESP to control it. In this scenario, you must set your ESP board as an access point.

Access Point

When you set your ESP32 board as an access point, you can be connected using any device with Wi-Fi capabilities without connecting to your router. When you set the ESP32 as an access point, you create its own Wi-Fi network, and nearby Wi-Fi devices (stations) can connect to it, like your smartphone or computer. So, you don’t need to be connected to a router to control it.

This can be also useful if you want to have several ESP32 devices talking to each other without the need for a router.

ESP32 Access Point Mode

Because the ESP32 doesn’t connect further to a wired network like your router, it is called soft-AP (soft Access Point). This means that if you try to load libraries or use firmware from the internet, it will not work. It also doesn’t work if you make HTTP requests to services on the internet to publish sensor readings to the cloud or use services on the internet (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);

ssid is the name you want to give to the ESP32 access point, and the password variable is the password for the access point. If you don’t want to set a password, set it to NULL.

There are also other optional parameters you can pass to the softAP() method. Here are all the parameters:

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;
  • password: minimum 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:

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

The ESP32 can scan nearby Wi-Fi networks within its Wi-Fi range. In your Arduino IDE, go to File > Examples > WiFi > WiFiScan. This will load a sketch that scans Wi-Fi networks within the range of your ESP32 board.

ESP32 Scan WiFi Networks

This can be useful to check if the Wi-Fi network you’re trying to connect is within the range of your board or other applications. Your Wi-Fi project may not often work because it may not be able to connect to your router due to insufficient Wi-Fi strength.

Here’s the example:

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

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

View raw code

You can upload it to your board and check the available networks as well as the RSSI (received signal strength indicator).

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

int n = WiFi.scanNetworks();

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

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

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

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

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

Finally, WiFi.encryptionType() returns the network encryption type. That specific example puts a * in the case of open networks. However, that function can return one of the following options (not just open networks):

  • 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

To connect the ESP32 to a specific Wi-Fi network, you must know its SSID and password. Additionally, that network must be within the ESP32 Wi-Fi range (to check that, you can use the previous example to scan Wi-Fi networks).

You can use the following function to connect the ESP32 to a Wi-Fi network initWiFi():

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 hold the SSID and password of the network you want to connect to.

// 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 it Works?

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

First, set the Wi-Fi mode. If the ESP32 will connected to another network (access point/hotspot) it 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 can take a while, so we usually add a while loop that keeps checking if the connection was already established by using WiFi.status(). When the connection is successfully established, it returns WL_CONNECTED.

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

Get Wi-Fi Connection Status

To get the status of the Wi-Fi connection, you can use WiFi.status(). This returns one of the following values that correspond to the constants on the table:

ValueConstantMeaning
0WL_IDLE_STATUStemporary status assigned when WiFi.begin() is called
1WL_NO_SSID_AVAIL when no SSID are available
2WL_SCAN_COMPLETEDscan networks is 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

To get the WiFi connection strength, you can simply call WiFi.RSSI() after a WiFi connection.

Here’s an example:

/*
  Complete details at https://RandomNerdTutorials.com/esp32-useful-wi-fi-functions-arduino/
*/

#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:
}

View raw code

Insert your network credentials and upload the code.

Open the Serial Monitor and press the ESP32 on-board RST button. It will connect to your network and print the RSSI (received signal strength indicator).

Get ESP32 Wi-Fi Connection Strength

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

Get ESP32 IP Address

When the ESP32 is set as a Wi-Fi station, it can connect to other networks (like your router). In this scenario, the router assigns a unique IP address to your ESP32 board. To get your board’s IP address, you need to call WiFi.localIP() after establishing a connection with your network.

Serial.println(WiFi.localIP());

Set a Static ESP32 IP Address

Instead of getting a randomly assigned IP address, you can set an available IP address of your preference to the ESP32 using WiFi.config().

Outside the setup() and loop() functions, define the following variables with your own static IP address and corresponding gateway IP address. By default, the following code assigns the IP address 192.168.1.184 that works in the gateway 192.168.1.1.

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

Alternatively, you can also try to restart the ESP32 with ESP.restart() when the connection is lost.

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

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 declare the previousMillis and interval variables. The interval corresponds to the period of time between each check in milliseconds (for example 30 seconds):

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

Here’s a complete example.

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/solved-reconnect-esp32-to-wifi/
  
  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("RRSI: ");
  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;
  }
}

View raw code

This example shows how to connect to a network and checks every 30 seconds if it is still connected. If it isn’t, it disconnects and tries to reconnect again.

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

Alternatively, you can also use WiFi Events to detected that the connection was lost and call a function to handle what to do when that happens (see the next section).

ESP32 Wi-Fi Events

The ESP32 can handle all the following Wi-Fi events:

0SYSTEM_EVENT_WIFI_READYESP32 Wi-Fi ready
1SYSTEM_EVENT_SCAN_DONEESP32 finish scanning AP
2SYSTEM_EVENT_STA_STARTESP32 station start
3SYSTEM_EVENT_STA_STOPESP32 station stop
4SYSTEM_EVENT_STA_CONNECTEDESP32 station connected to AP
5SYSTEM_EVENT_STA_DISCONNECTEDESP32 station disconnected from AP
6SYSTEM_EVENT_STA_AUTHMODE_CHANGEthe auth mode of AP connected by ESP32 station changed
7SYSTEM_EVENT_STA_GOT_IPESP32 station got IP from connected AP
8SYSTEM_EVENT_STA_LOST_IPESP32 station lost IP and the IP is reset to 0
9SYSTEM_EVENT_STA_WPS_ER_SUCCESSESP32 station wps succeeds in enrollee mode
10SYSTEM_EVENT_STA_WPS_ER_FAILEDESP32 station wps fails in enrollee mode
11SYSTEM_EVENT_STA_WPS_ER_TIMEOUTESP32 station wps timeout in enrollee mode
12SYSTEM_EVENT_STA_WPS_ER_PINESP32 station wps pin code in enrollee mode
13SYSTEM_EVENT_AP_STARTESP32 soft-AP start
14SYSTEM_EVENT_AP_STOPESP32 soft-AP stop
15SYSTEM_EVENT_AP_STACONNECTEDa station connected to ESP32 soft-AP
16SYSTEM_EVENT_AP_STADISCONNECTEDa station disconnected from ESP32 soft-AP
17SYSTEM_EVENT_AP_STAIPASSIGNEDESP32 soft-AP assign an IP to a connected station
18SYSTEM_EVENT_AP_PROBEREQRECVEDReceive probe request packet in soft-AP interface
19SYSTEM_EVENT_GOT_IP6ESP32 station or ap or ethernet interface v6IP addr is preferred
20SYSTEM_EVENT_ETH_STARTESP32 ethernet start
21SYSTEM_EVENT_ETH_STOPESP32 ethernet stop
22SYSTEM_EVENT_ETH_CONNECTEDESP32 ethernet phy link up
23SYSTEM_EVENT_ETH_DISCONNECTEDESP32 ethernet phy link down
24SYSTEM_EVENT_ETH_GOT_IPESP32 ethernet got IP from connected AP
25SYSTEM_EVENT_MAX

For a complete example on how to use those events, in your Arduino IDE, go to File > Examples > WiFi > WiFiClientEvents.

/*
   This sketch shows the WiFi event usage - Example from WiFi > WiFiClientEvents
   Complete details at https://RandomNerdTutorials.com/esp32-useful-wi-fi-functions-arduino/
*/

/*
* WiFi Events
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
*/

#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 SYSTEM_EVENT_WIFI_READY: 
      Serial.println("WiFi interface ready");
      break;
    case SYSTEM_EVENT_SCAN_DONE:
      Serial.println("Completed scan for access points");
      break;
    case SYSTEM_EVENT_STA_START:
      Serial.println("WiFi client started");
      break;
    case SYSTEM_EVENT_STA_STOP:
      Serial.println("WiFi clients stopped");
      break;
    case SYSTEM_EVENT_STA_CONNECTED:
      Serial.println("Connected to access point");
      break;
    case SYSTEM_EVENT_STA_DISCONNECTED:
      Serial.println("Disconnected from WiFi access point");
      WiFi.begin(ssid, password);
      break;
    case SYSTEM_EVENT_STA_AUTHMODE_CHANGE:
      Serial.println("Authentication mode of access point has changed");
      break;
    case SYSTEM_EVENT_STA_GOT_IP:
      Serial.print("Obtained IP address: ");
      Serial.println(WiFi.localIP());
      break;
    case SYSTEM_EVENT_STA_LOST_IP:
      Serial.println("Lost IP address and IP address is reset to 0");
      break;
    case SYSTEM_EVENT_STA_WPS_ER_SUCCESS:
      Serial.println("WiFi Protected Setup (WPS): succeeded in enrollee mode");
      break;
    case SYSTEM_EVENT_STA_WPS_ER_FAILED:
      Serial.println("WiFi Protected Setup (WPS): failed in enrollee mode");
      break;
    case SYSTEM_EVENT_STA_WPS_ER_TIMEOUT:
      Serial.println("WiFi Protected Setup (WPS): timeout in enrollee mode");
      break;
    case SYSTEM_EVENT_STA_WPS_ER_PIN:
      Serial.println("WiFi Protected Setup (WPS): pin code in enrollee mode");
      break;
    case SYSTEM_EVENT_AP_START:
      Serial.println("WiFi access point started");
      break;
    case SYSTEM_EVENT_AP_STOP:
      Serial.println("WiFi access point  stopped");
      break;
    case SYSTEM_EVENT_AP_STACONNECTED:
      Serial.println("Client connected");
      break;
    case SYSTEM_EVENT_AP_STADISCONNECTED:
      Serial.println("Client disconnected");
      break;
    case SYSTEM_EVENT_AP_STAIPASSIGNED:
      Serial.println("Assigned IP address to client");
      break;
    case SYSTEM_EVENT_AP_PROBEREQRECVED:
      Serial.println("Received probe request");
      break;
    case SYSTEM_EVENT_GOT_IP6:
      Serial.println("IPv6 is preferred");
      break;
    case SYSTEM_EVENT_ETH_START:
      Serial.println("Ethernet started");
      break;
    case SYSTEM_EVENT_ETH_STOP:
      Serial.println("Ethernet stopped");
      break;
    case SYSTEM_EVENT_ETH_CONNECTED:
      Serial.println("Ethernet connected");
      break;
    case SYSTEM_EVENT_ETH_DISCONNECTED:
      Serial.println("Ethernet disconnected");
      break;
    case SYSTEM_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::SYSTEM_EVENT_STA_GOT_IP);
  WiFiEventId_t eventID = WiFi.onEvent([](WiFiEvent_t event, WiFiEventInfo_t info){
    Serial.print("WiFi lost connection. Reason: ");
    Serial.println(info.disconnected.reason);
  }, WiFiEvent_t::SYSTEM_EVENT_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);
}

View raw code

With Wi-Fi Events, you don’t need to be constantly checking the Wi-Fi state. When a certain event happens, it automatically calls the corresponding handling function.

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

Wi-Fi events can be useful to detect that a connection was lost and try to reconnect right after (use the SYSTEM_EVENT_AP_STADISCONNECTED event). Here’s a sample code:

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/solved-reconnect-esp32-to-wifi/
  
  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.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, SYSTEM_EVENT_STA_CONNECTED);
  WiFi.onEvent(WiFiGotIP, SYSTEM_EVENT_STA_GOT_IP);
  WiFi.onEvent(WiFiStationDisconnected, SYSTEM_EVENT_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);
}

View raw code

How it Works?

In this example we’ve added three Wi-Fi events: when the ESP32 connects, when it gets an IP address, and when it disconnects: SYSTEM_EVENT_STA_CONNECTED, SYSTEM_EVENT_STA_GOT_IP, SYSTEM_EVENT_STA_DISCONNECTED.

When the ESP32 station connects to the access point (SYSTEM_EVENT_STA_CONNECTED event), the WiFiStationConnected() function will be called:

WiFi.onEvent(WiFiStationConnected, SYSTEM_EVENT_STA_CONNECTED);

The WiFiStationConnected() function simply prints that the ESP32 connected to an access point (for example, your router) successfully. However, you can modify the function to do any other task (like light up 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, SYSTEM_EVENT_STA_GOT_IP);

That function simply prints the IP address son 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 (SYSTEM_EVENT_STA_DISCONNECTED), the WiFiStationDisconnected() function is called.

WiFi.onEvent(WiFiStationDisconnected, SYSTEM_EVENT_STA_DISCONNECTED);

That function prints a message indicating that the connection was 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.disconnected.reason);
  Serial.println("Trying to Reconnect");
  WiFi.begin(ssid, password);
}

Wrapping Up

This article was a compilation of some of the most used and useful ESP32 Wi-Fi functions. Although there are plenty of examples of using the ESP32 Wi-Fi capabilities, there is little documentation explaining how to use the Wi-Fi functions with the ESP32 using Arduino IDE. So, we’ve decided to put together this guide to make it easier to use ESP32 Wi-Fi related functions in your projects.

If you have other useful suggestions, you can share them on the comments’ section.

We hope you’ve found this tutorial useful.

Learn more about the ESP32 with our resources:



Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »

Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our weekly newsletter!

34 thoughts on “ESP32 Useful Wi-Fi Library Functions (Arduino IDE)”

  1. Hi
    Your blog is very interresting and helps a lot, but i miss the information to change the hostname of the esp32. Is it possible to change the Espressif unit name to a project specifish name.
    I know i can change the name in the wlan router but the unit name still is Espressif

    Regards

    Reply
  2. Is there a way to quickly do a WiFi Scan for a SPECIFIC SSID and, when it detects the WiFi SSID is available (or not), does something with this information in the sketch?

    Reply
    • Hi Jim,

      Something like that?

      #include <Arduino.h>
      #include <WiFi.h>

      const char* SPECIFIC_SSID = "MyNetwork";
      const char* ENC_TYPE[] = {
      "Open",
      "WEP",
      "WPA_PSK",
      "WPA2_PSK",
      "WPA_WPA2_PSK",
      "WPA2_ENTERPRISE",
      "MAX"
      };

      struct WiFiInfo {
      bool found;
      int32_t channel;
      int32_t rssi;
      wifi_auth_mode_t auth_mode;
      } wifi_info;

      void findWiFi(const char *ssid, WiFiInfo *info) {
      info->found = false;
      int16_t n = WiFi.scanNetworks();
      for (uint8_t i=0; i<n; ++i) {
      if (strcmp(WiFi.SSID(i).c_str(), ssid) == 0) {
      info->found = true;
      info->channel = WiFi.channel(i);
      info->rssi = WiFi.RSSI(i);
      info->auth_mode = WiFi.encryptionType(i);
      return;
      }
      }
      }

      void setup() {
      Serial.begin(115200);
      findWiFi(SPECIFIC_SSID, &wifi_info);
      Serial.printf(wifi_info.found
      ? "SSID: %s, channel: %i, RSSI: %i dBm, encryption: %s\n"
      : "SSID: %s ... could not be found\n",
      SPECIFIC_SSID,
      wifi_info.channel,
      wifi_info.rssi,
      ENC_TYPE[wifi_info.auth_mode]);
      }

      void loop() {}

      Reply
      • This worked perfectly. Thank you! I wonder if there is a faster way to get the SSID without having to scan for all networks first, and then isolating the network I’m searching for. Is there a way to do this?

        Reply
  3. To use as a WiFi reference, there is a couple of things I would’ve liked to see included; i.e., commands to manipulate the MAC address of a board, and an example using the soft_AP and STA modes together.

    As Werner noted, if there is a way to redefine the identifier, that would be great to know too!

    That said, it is still a great article, and I would love to see it expanded with more examples of the more obscure commands’ responses. Maybe a downloadable table of the command/method/event, use format, possible responses, and any comments (such as “only valid in STA mode” or, a link to an example. Most of this is already in the article, just not well summarized, so hard to locate.

    Cheers!

    Reply
  4. Great tutorial!
    Thanks for your work.
    I found the automatic reconnection feature after the card disconnected very interesting. However, they seem to understand that this doesn’t always work. Especially when using Blynk. Has anyone had any experience in this regard?
    Greetings. Mike.

    Reply
  5. Is it now possible to run ESP-Now together with WiFi in STA mode?
    My last state was: ESP-Now and WiFi must share the same channel and the channel number must be 1. Even when the router starts a connection at channel 1 in STA mode, if the router changes the channel to avoid traffic collisions, the ESP-Now connection breaks.

    Reply
  6. Great Tutorial!
    I am having some trouble connecting to my local WiFi and I’m sure this info will help me understand what is happening.

    Do you have something similar for the ESP8266?

    Reply
  7. What I would find most useful would be some sample code that:

    attempted a connection with stored network ID and credentials
    if this failed fall back to AP mode, so that a user can connect, login to a webUI, save new network details, and then reboot / attempt to reconnect.

    No-one want to recompile code, just so a device can change networks.

    Reply
  8. It’s a pity that you omitted WiFi.persistent() command. I think, that this function is one of the most important when using WiFi and literally nobody knows about it.

    In short: This function is true on default and causes, that every time (on every reboot) when calling WiFi.begin the ssid+pass are written into flash. This is a flash killer when using WiFi and deepsleep together.

    Reply
  9. Hi,
    Thank you for publishing the article.
    Regarding Reconnect to Wi-Fi Network After Lost Connection code
    I have a need to modify the while loop so it checks for two conditions for example
    (WiFi.status() != WL_CONNECTED) or (WiFi.status() != WL_NO_SSID_AVAIL)

    Could you advice me of the best approach

    Best regards

    Reply
  10. I have found that setting a static IP address in Station mode sometimes works, and sometimes not. I guess it depends on the router and a bunch of advanced network stuff that I dont understand. Nevertheless: this means for a user who wants to access the ESP32 webserver page, he/she must know the IP. How do you solve this when that user does not have access to the serial print nor some ESP-attached display?

    A static IP address would be a great solution, but it is just not reliable enough. I have also tried with mDNS and also that was unreliable (worked on iPhone but not Android).

    This is a use case where I would give a project as a gift to someone who doesnt know Arduino and can’t expect them to read Serial monitor or something like that. I haven’t found a true solution to this problem anywhere. How do you solve it?

    Reply
  11. Hi
    Thank you for publishing the article. Regarding the while loop I have a need to modify the while loop so it checks for two conditions for example
    (WiFi.status() != WL_CONNECTED) or (WiFi.status() != WL_NO_SSID_AVAIL)

    Could you advice me of the best approach

    Best Regards

    Reply
  12. Is there a way to show my gratitude, Rui and Sara? The books and tutorials that you produce are nothing short of fantastic. It’s a joy to work on a project that incorporates your work knowing that you have published information and code that is accurate and complete. You two are making a huge impact on the world of IOT and data networking that will advance the technology as well as advance the knowledge of thousands of us nerds! Thank you for what you do for the world every day!

    Reply

Leave a Comment

Download our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.