[Resolve] Reconnect ESP32 to Wi-Fi Network After Lost Connection

This fast article shows you how to reconnect ESP32 to Wi-Fi Network After losing the Connection. This may be useful in the following circumstances: the ESP32 temporarily loses Wi-Fi signal; the ESP32 is temporarily out of range of the router's Wi-Fi; the router restarts; the router loses internet connection; or other conditions.

We have a similar guide for the ESP8266 NodeMCU board:

  • [SOLVED] Reconnect ESP8266 NodeMCU to Wi-Fi Network After Lost Connection (SOON)

You should also take a look at WiFiMulti. You may register multiple networks (SSID/password combinations) using it. The ESP32 will connect to the Wi-Fi network that has the strongest signal strength (RSSI). If the connection is lost, it will automatically connect to the next network in the list. Read this article: ESP32 WiFiMulti: Connect to the Strongest Wi-Fi Network (from a list of networks). 

lilygo Official Store

Reconnect to Wi-Fi Network After Lost Connection

You may use WiFi to reconnect once a connection is lost. WiFi.reconnect() is used to try to reconnect to a 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 to the loop(), like the snippet below, that checks once in a while whether the board is connected and tries to reconnect if it has lost connection.

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. In milliseconds (for instance, 30 seconds), the interval represents the period of time between each check:

keyestudio Official Store

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 make sure it's still connected. If not, it disconnects and tries to reconnect.

Alternatively, you may use Wi-Fi Events to detect a lost connection and call a function to handle what to do when that happens (see the next section).

ESP32 Wi-Fi Events

The ESP32 can handle a variety of Wi-Fi events. Wi-Fi Events eliminate the need to continually check the Wi-Fi status. When an event occurs, the associated handling function is automatically called.

The following events are very useful to detect if the connection was lost or reestablished:

TSCINBUNY Official Store

  • ARDUINO_EVENT_WIFI_STA_CONNECTED: the ESP32 is connected in station mode to an access point/hotspot (your router);
  • ARDUINO_EVENT_WIFI_STA_DISCONNECTED: the ESP32 station disconnected from the access point.

Go to the next section to see an application example.

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

Wi-Fi events might be useful to identify when a connection has been lost and to try to reconnect later (use the ARDUINO_EVENT_WIFI_STA_DISCONNECTED event). A sample of the code is shown below:

/*
  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 does it work?

We've included three Wi-Fi events in this example: when the ESP32 connects when it obtains an IP address, and when it disconnects: ARDUINO_EVENT_WIDI_STA_CONNECTED, ARDUINO_EVENT_WIFI_STA_GOT_IP, and 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 (like your router, for example). However, you may change the function to do any other task (such as turning on an LED to show that it has 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 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.disconnected.reason);
  Serial.println("Trying to Reconnect");
  WiFi.begin(ssid, password);
}

Conclusion

The following is a list of all the ways that the ESP32 may be used to reconnect the lost connection.

To better understand some of the most commonly used ESP32 Wi-Fi functions, we recommend that you take a look at the following tutorial:

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