X

Reconnect ESP32 to WIFI after Lost Connection (Solved)

In this tutorial, we will learn how to reconnect the ESP32 board to the WIFI network when it temporarily loses connection. Through different methods, we will demonstrate this functionality. Hence, this guide will be highly useful to avoid the nuisance of constantly losing network connection due to many reasons such as WiFi router restarted, ESP32 is out of range of WiFi router, router loses power and restarts.

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:

1st Method: WiFi.reconnect() function

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

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

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

  • The name of your WIFI network known as SSID is the first argument.
  • Second argument is the password of your associated WIFI network. Make sure to specify the functions in the correct sequence.

2nd Method: ESP.restart()

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

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

Arduino Sketch

Follow the Arduino sketch given below. The infinite loop() function will perform the aforementioned functionality. After every 20 seconds, it will check whether the board is still connected with 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 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.

3rd Method: ESP32 WiFi Events

The infinite loop() method stated above will help recover the lost WIFI connection but is slightly inconvenient and wastage of ESP32 resources. For a better approach, we will try to 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.

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.

Arduino Sketch

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 the Code Works?

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 the 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 parameters 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 with 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 detect it and reconnect.

Reconnect ESP32 to WIFI demo
Serial Monitor

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 reconnet with WiFi makes it useful for web server projects.

You can read this web server projects with ESP32:

Leave a Comment