Reconnect ESP32 to WiFi after Lost Connection (Solved)

In this tutorial, we’ll find out how to make sure that the ESP32 device stays connected to the Wi-Fi network even if the connection is lost temporarily. In other words, how to reconnect the ESP32 board to the WIFI network when it temporarily loses connection. We’ll achieve this by using different techniques that help the ESP32 reconnect to Wi-Fi automatically. This tutorial will be very helpful because it prevents the annoyance of having the ESP32 repeatedly lose its network connection for various reasons, like when the Wi-Fi router is turned off and on again, when the ESP32 moves too far from the router, or when the router itself loses power and restarts. By following this guide, you can ensure that your ESP32 device maintains a reliable connection to the Wi-Fi network.

ESP32 Reconnect to Wi-Fi Network After Lost Connection

We have a similar guide with ESP8266 NodeMCU:

Reconnect ESP8266 NodeMCU to WIFI after Lost Connection (Solved)

As mentioned before, we will use different techniques to reconnect ESP32 to a WiFi connection after lost Connection. You can use any suitable one from the list given below:

ESP32 WiFi.reconnect() Function (1st Method)

In your ESP32 code, use WiFi.connect() function to regain connection to the network to which the ESP32 board was previously connected.

WiFi.reconnect()

You can also use WiFi.disconnect() function and then WiFi.begin(ssid,password) in same order. The WiFi.begin(ssid, password) function will take in two arguments.

WiFi.disconnect()
WiFi.begin(ssid,password):
  • The name of your WIFI network known as SSID is the first argument.
  • The second argument is the password of your associated WIFI network. Make sure to specify the functions in the correct sequence.

ESP32 Reconnect Wi-Fi with ESP.restart() (2nd Method)

The alternative way to reconnect with WiFi is to restart the ESP32 device. By using ESP.restart() function, we can restart the ESP32 development board. This may recover the lost network connection.

Implement the ESP.restart() function inside the loop() function to check if your ESP module is connected to the WiFi. If the connection is lost, it reconnects through WiFi.reconnect() function.

ESP32 Code

The infinite loop() function will perform the aforementioned functionality. After every 20 seconds, it will check whether the board is still connected to the WIFI or not. If not then it will try reconnecting by first disconnecting and then attempting to reconnect.

#include <WiFi.h>

const char* ssid = "Your_SSID";
const char* password = "Your_Password";

unsigned long previous_time = 0;
unsigned long delay = 20000;  // 20 seconds delay

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

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

void loop() {
  unsigned long current_time = millis(); // number of milliseconds since the upload

  // checking for WIFI connection
  if ((WiFi.status() != WL_CONNECTED) && (current_time – previous_time >=delay)) {
    Serial.print(millis());
    Serial.println("Reconnecting to WIFI network");
    WiFi.disconnect();
    WiFi.reconnect();
    previous_time = current_time;
  }
}

You can increase the recheck time by changing the delay value in the following line:

unsigned long delay = 20000; // 20 seconds delay

This method is a good solution to reconnect WiFi to ESP32 if the connection loses accidentally. But with this method, we have to poll if ((WiFi.status() != WL_CONNECTED) && (current_time – previous_time >=delay)) condition on every execution of loop().

The alternative to loop() method is using ESP32 WIFI Events. We will show in detail another useful feature known as WIFI Events. It will help in detecting the lost network connection. Additionally, a function will be called to manage a successful reconnection. This is discussed in the section below.

ESP32 WiFi Events (3rd Method)

The infinite loop() method stated above will help recover the lost WIFI connection but is slightly inconvenient and a wastage of ESP32 resources. For a better approach, we can use ESP32 WIFI Events instead. The WIFI Events will directly detect the absence of WIFI. Also, it will simultaneously call a handling function to reconnect to the network.

WiFi Events Introduction

ESP32 WiFi library provides a way to handle Wi-Fi events, allowing you to respond to various changes and conditions related to WiFi.

How to use W-Fi Events?

ESP32 Wi-Fi events refer to notifications generated by the ESP32 when there are changes or updates related to its Wi-Fi connectivity. These events inform you about important occurrences such as successful connections, disconnections, authentication failures, and more. By monitoring and responding to these events, we can create more robust and responsive applications that adapt to different network scenarios. This capability helps us reconnect ESP32 to a Wi-Fi network with an event-driven approach.

For detection and reconnection purposes, two WIFI events come in very handy. These are given below.

  1. SYSTEM_EVENT_STA_CONNECTED: The ESP32 is in station mode and is connected to an access point (AP).
  2. SYSTEM_EVENT_STA_DISCONNECTED: The ESP32 is in station mode and is disconnected from the access point (AP).

We will use an Arduino sketch to explain how WIFI Events will work. Through these events, the ESP32 will be able to reconnect with the router instantaneously after losing connection. We will use the two above-mentioned events in this regard.

ESP32 Code

Open your Arduino IDE and go to File > New to open a new file. Copy the code given below in that file. This code will work for your ESP32 development board. You have to replace the network credentials.

#include <WiFi.h>
const char* ssid = "Your_SSID";
const char* password = "Your_Password";

void Wifi_connected(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("Successfully connected to Access Point");
}

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

void Wifi_disconnected(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("Reconnecting...");
  WiFi.begin(ssid, password);
}

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

  WiFi.onEvent(Wifi_connected,SYSTEM_EVENT_STA_CONNECTED);
  WiFi.onEvent(Get_IPAddress, SYSTEM_EVENT_STA_GOT_IP);
  WiFi.onEvent(Wifi_disconnected, SYSTEM_EVENT_STA_DISCONNECTED); 
  WiFi.begin(ssid, password);
  Serial.println("Waiting for WIFI network...");
}

void loop(){
  delay(1000);
}

How does the Code Work?

Firstly, we will include the WiFi.h library. This library will help in establishing the connection between our ESP32 module to a wireless network.

#include <WiFi.h>

Next, we will create two global variables, one for the SSID and the other for the password. These will hold our network credentials which will be used to connect to our wireless network. Replace both of them with your credentials to ensure a successful connection.

const char* ssid = "Your_SSID";
const char* password = "Your_Password";
User Defined Functions

Then we will define some functions which we will need to call later on in the code. Firstly, we will define the Wifi_connected() function. This function will be called when our ESP32 will connect to an access point through the SYSTEM_EVENT_STA_CONNECTED event. This function will print: “Successfully connected to Access Point” in our serial monitor.

void Wifi_connected(WiFiEvent_t event, WiFiEventInfo_t info){
  Serial.println("Successfully connected to Access Point");
}

Secondly, we will define the Get_IPAddress() function. This will be called when our ESP32 board will use the event SYSTEM_EVENT_STA_GOT_IP to access its IP address. Through this Get_IPAddress() function we will print ‘WIFI is connected!” and the IP address of our module on the serial monitor.

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

Lastly, we will define the Wifi_disconnected() function. This function will be called when our ESP32 will disconnect from an access point through the SYSTEM_EVENT_STA_DISCONNECTED event. This function will print “Disconnected from WIFI access point”. It will also specify the reason in a code number for the disconnection. Additionally, it will also try to reconnect with the network through the WiFi.begin() function.

void Wifi_disconnected(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("Reconnecting...");
  WiFi.begin(ssid, password);
}
Setup() Function

Inside the setup() function we will open the serial communication at a baud rate of 115200.

Serial.begin(115200);

Then we will call WiFi.disconnect() function with true as a parameter inside it. This will delete all the previous network credentials stored in the board.

WiFi.disconnect(true);

Next, we will call WiFi.onEvent() function for all three WIFI Events. These will be SYSTEM_EVENT_STA_CONNECTED, SYSTEM_EVENT_STA_GOT_IP and SYSTEM_EVENT_STA_DISCONNECTED. We will individually pass them as the second parameter inside the WiFi.onEvent() function. The previously user-defined functions will act as the first parameters.

WiFi.onEvent(Wifi_connected,SYSTEM_EVENT_STA_CONNECTED);
WiFi.onEvent(Get_IPAddress, SYSTEM_EVENT_STA_GOT_IP);
WiFi.onEvent(Wifi_disconnected, SYSTEM_EVENT_STA_DISCONNECTED); 

Then we will connect our ESP32 board to the access point through the WiFi.begin() function.

  WiFi.begin(ssid, password);
  Serial.println("Waiting for WIFI network...");

Demonstration

Make sure you choose the correct board and COM port before uploading your code to the board. Go to Tools > Board and select ESP32 Dev Module. Next, go to Tools > Port and select the appropriate port through which your board is connected.
Click on the upload button to upload the code into the ESP32 development board.
After you have uploaded your code to the development board, press its ENABLE button.

Open your Serial Monitor at a baud rate of 115200. Now connect to your local WIFI network. Disrupt the connection. The program code /automatically detects it and reconnects.

Reconnect ESP32 to WIFI demo
Serial Monitor

ESP32 Use Multiple Wi-Fi Networks ( Method 4)

You might also be interested in exploring a feature called WiFiMulti. This feature lets you save multiple Wi-Fi networks along with their respective passwords. With WiFiMulti, the ESP32 will automatically connect to the Wi-Fi network that has the strongest signal strength (measured using RSSI). If the ESP32 ever loses its connection to the current network, it will then attempt to connect to the next network in the list. This can be particularly helpful in situations where you have several available Wi-Fi networks, ensuring that your ESP32 maintains a stable connection. You can learn more about this by reading the following guide:

If you want to connect ESP32 to a network through a mobile app, you can follow this guide:

Summary:

In this tutorial, we have discussed three different methods to reconnect ESP32 to Wi-Fi Network after a lost connection. The capability of ESP32 to reconnect with WiFi makes it useful for web server projects.

You can read this web server projects with ESP32:

1 thought on “Reconnect ESP32 to WiFi after Lost Connection (Solved)”

  1. This is very useful – thank you for documenting. On the 3rd option, WiFi Events, will the ESP continue to execute its code while trying to reconnect? I use the wifi to store data on a remote db, but if the wifi is down, I still need the code to work and perform other functions.

    Reply

Leave a Comment