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

This quick guide shows how you can reconnect your ESP32 to a Wi-Fi network after losing the connection. This can be useful in the following scenarios: the ESP32 temporarily loses Wi-Fi signal; the ESP32 is temporarily out of the router’s Wi-Fi range; the router restarts; the router loses internet connection or other situations.

ESP32 Reconnect to Wi-Fi After Lost Connection 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 the loop() that checks once in a while if 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 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.

Alternatively, you can also use Wi-Fi Events to detect 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 is able 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 following events are very useful to detect if the connection was lost or reestablished:

  • SYSTEM_EVENT_STA_CONNECTED: the ESP32 is connected in station mode to an access point/hotspot (your router);
  • SYSTEM_EVENT_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 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, and SYSTEM_EVENT_STA_DISCONNECTED, respectively.

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 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 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 quick tutorial shows different ways on how you can reconnect your ESP32 to a Wi-Fi network after the connection is lost.

We recommend that you take a look at the following tutorial to better understand some of the most used ESP32 Wi-Fi functions:

One of the best applications of the ESP32 Wi-Fi capabilities is building web servers. If you want to use the ESP32 or ESP8266 boards to build Web Server projects, you might like our eBook:

We hope you’ve found this tutorial useful.

Thanks for reading.



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!

24 thoughts on “[SOLVED] Reconnect ESP32 to Wi-Fi Network After Lost Connection”

  1. Thank you for publishing this. Wifi problems are a significant problem on all remote monitoring systems. This will help solve that. I am working a project to
    Remotely control and test my router and modem using sim7000 cell device. I
    Wish you would consider developing a tutorial on this subject, I’m sure it would be helpful to man developers.

    Reply
    • Hi.
      Tomorrow we’ll publish a more complete tutorial about Wi-Fi functions. You may find it useful.
      I’ll add the SIM700 to my list of future tutorials.
      Thanks for your comment.
      Regards,
      Sara

      Reply
  2. Thank You. This is great. I tried several programming to reconnect to Wi-Fi Network after lost connection, but didn’t know the Wi-Fi Events. I will try this.
    Greatings from Berlin
    Sigi

    Reply
    • Hi.
      The Wi-Fi library is different for the ESP8266. So, it is not compatible.
      I’ll have to write a similar tutorial for the ESP8266.
      Regards,
      Sara

      Reply
    • while you are awaiting Sara’s ESP8266 tutorial on the matter, there is a crude method of doing this:
      if (WiFi.status() == 6)
      {
      ESP.reset();
      }

      ‘6’ means WL_DISCONNECTED

      I believe it is also possible to use:
      WiFi.setAutoReconnect(true);
      WiFi.persistent(true);
      immediately after you get connected the first time, but I have not tried that myself, so maybe best to await Sara’s tutorial

      Reply
  3. Great advice. Could be the solution to my remote weather station losing connection after a power cut.
    Does the code work with a Wemos device??

    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.