Reconnect ESP32 to Wi-Fi Network After Lost Connection

Description

  • When working with an ESP32 device, there may be situations where the Wi-Fi connection is lost or disrupted. i.e. when the Wi-Fi router restarts or ESP32 goes out of network area and again comes back.
  • To handle such scenarios and ensure continuous connectivity, we need to use Wi-Fi.reconnect() function in proper order. This function attempt to reconnect the disconnected network.
  • If the connection is lost, it will attempt to reconnect to the configured network.
  • During the reconnect process, the ESP32 device will utilize the previously configured Wi-Fi credentials, including the SSID (network name) and password. 

 

There are few menthods to reconnect to Wi-Fi after a connection is lost, 

  1. We can use WiFi.reconnect() to try to reconnect to the previously connected access point:
WiFi.reconnect()

 

2. Or we can call it WiFi.disconnect() followed by WiFi.begin(ssid, password).

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

 

3. Alternatively, We can also try to restart the ESP32 with ESP.restart() when the connection is lost. However, ESP.restart() function shall not be first preference as it is resetting (Software Reset) the ESP32. 

ESP.restart() 

 

4. We can add something like the snippet below to the loop() that checks once in a while if the board is connected and tries to reconnect if it has lost connection. We can set the interval value like 30 seconds or 1 Minute.

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

 

5. We can use ESP32 Wi-Fi Events to handle different Wi-Fi events. 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. The example is given below (Example 2).

Before uploading the code make sure you have added your SSID and Password

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Reconnect wifi code for ESP32 Example 1

#include <WiFi.h>

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

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

void setup() {
 Serial.begin(115200);
 WiFi.mode(WIFI_STA);
 WiFi.begin(ssid, password);
 Serial.print("Connecting to ");
 Serial.println(ssid);
 delay(1000);
 while (WiFi.status() != WL_CONNECTED) {
   Serial.print('.');
   delay(500);
 }
 Serial.print("Connected to ");
 Serial.println(ssid);
 Serial.print("Your Local IP address is: ");
 Serial.println(WiFi.localIP());      /*Print the Local IP*/
}

void loop() {
 unsigned long currentMillis = millis();
 if ((WiFi.status() != WL_CONNECTED) && (currentMillis - previousMillis >=interval)) {
   Serial.println("Reconnecting to WiFi...");
   WiFi.disconnect();
   WiFi.reconnect();   
   previousMillis = currentMillis;
 }
}

 

  • Now upload the code. (While uploading the code make sure your ESP32 board is in the boot mode.)
  • After uploading the code open the serial monitor and set the baud rate to 115200 to see the output.

Output on serial Monitor

 

Let's understand the code

Add the required libraries

#include <WiFi.h>

 

Setup Function

In the setup function, Set the baud rate to 115200

Serial.begin(115200);

In the setup function, first, we set the WiFi as an STA mode and connect to the given SSID and password

WiFi.mode(WIFI_STA);         /*Set the WiFi in STA Mode*/
WiFi.begin(ssid, password);
Serial.print("Connecting to ");
Serial.println(ssid);
delay(1000);                  /*Wait for 1000mS*/
while(WiFi.waitForConnectResult() != WL_CONNECTED){Serial.print(".");}

After successfully connecting to the server print the local IP address on the serial window.

Serial.print("Your Local IP address is: ");
Serial.println(WiFi.localIP());    /*Print the Local IP*/

 

Loop Function

In the loop function check the wifi connection status, if the wifi is not connected then it will connect automatically.

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

 

Example 2

We can use ESP32 Wi-Fi Events to handle different Wi-Fi events. With Wi-Fi Events, we don’t need to be constantly checking the Wi-Fi state. 

When a certain event happens, Like WiFi Disconnect, it automatically calls the corresponding handling function like to re-establish Wi-Fi Connection.

In the below code, you will find that we have added an event like WiFiStationDisconnected and when it will occur, the corresponding handling function will be executed.

Reconnect wifi code for ESP32 Example 2

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

 

  • Now upload the code. (While uploading the code make sure your ESP32 board is in the boot mode.)
  • After uploading the code open the serial monitor and set the baud rate to 115200 to see the output.

Output on serial Monitor

let’s understand the code

Add the required libraries

#include <WiFi.h>

Below are three events added for ESP32 connects, Get IP address, and wifi disconnected: ARDUINO_EVENT_WIDI_STA_CONNECTED, ARDUINO_EVENT_WIFI_STA_GOT_IP, and ARDUINO_EVENT_WIFI_STA_DISCONNECTED, respectively.

When ESP32 is connecting to the wifi then the below event will be called:

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

After ESP32 Wi-Fi connect, this event function will be excecuted:

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

ESP32 IP address function is below.

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 below event occur

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

ESP32 lost the wifi connection and tried to reconnect the below function run.

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

Components Used

ESP32 WROOM
WiFi Development Tools - 802.11 ESP32 General Development Kit, embeds ESP32-WROOM-32E, 4MB flash.
1

Downloads

WiFi_Reconnect_Example_1 Download
WiFi_Reconnect_Example_2 Download
Ad