[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

We have a similar guide for the ESP8266 NodeMCU board:

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 »

Recommended Resources

Build a Home Automation System from Scratch » With Raspberry Pi, ESP8266, Arduino, and Node-RED.

Home Automation using ESP8266 eBook and video course » Build IoT and home automation projects.

Arduino Step-by-Step Projects » Build 25 Arduino projects with our course, even with no prior experience!

What to Read Next…


Enjoyed this project? Stay updated by subscribing our newsletter!

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

      • Hi Sara, I hope you can help me with this issue, my ESP32 does not connect with no one access point, not matter what I had tried the device does not connect, using your tutorial I am getting the error “disconnected from WIFI access point”, any idea I can try? thanks

        Reply
  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
      • Hi Ed.
        Yes, you can use
        WiFi.setAutoReconnect(true);
        WiFi.persistent(true);
        Right after connecting to Wi-Fi.
        When the connection is lost, it will automatically reconnect.
        Regards,
        Sara

        Reply
        • I’ve just looked at the tutorial for ESP8266 and see the snipped is exactly the same: Put after this line:
          Serial.println(WiFi.localIP());
          //The ESP8266 tries to reconnect automatically when the connection is lost
          WiFi.setAutoReconnect(true);
          WiFi.persistent(true);

          Is this correct ?

          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
  4. Living close to an airport, my router occasionally disconnects the 5 GHz band for one minute due to RADAR priority, resetting the whole WiFi. Your tutorial shows how to handle this.
    Thank you!

    Reply
  5. Great Job Rui and Sara,

    you are doing a great Job, this website is the first place I check when I am stuck with some thing, your tutorials helped me a lot with my projects,

    Thanks a lot for all the efforts, keep the good work coming

    Thanks

    Reply
  6. hi sara im facing a problem with wifi reconnecting after a deep sleep mode . the first 1-2hrs it gave me the reading but not same time after it wake up but thats fine im ok but the problem here is after 2 hrs it just reconnecting only not connected ….

    Reply
  7. Hello Sara,

    I have a slightly different issue with wifi and esp32. I have a project with the esp32 where it connects itself to my wifi. After uploading the code everything works perfectly. I can turn on and off the board with a switch and it will always work. The next day when i turn on the device again it cant connect to my local network. No matter how many times i turn on/off it wont work. I have to reboot my wifi repeater in order for the board to find the wifi network again. Have you already faced a similar issue?

    Reply
    • Hello,

      This behaviour of ESP modules is often observed. They try to connect after power cycling to a router (Asus, Unifi, Netgear, etc.) that is configured as a DHCP server but get no connection until the router is rebooted.

      Sometimes the solution is to assign a static IP to the ESP module (e.g. 192.168.1.xx) but then linked to the module itself (“hardware” programmed into the module) because an IP reservation (linked to MAC address in the router’s firmware) seems to achieve the same thing, is easy to realise but remains DHCP and therefore does not work.

      Greetings

      Reply
      • Hello Roland,

        I have followed your advice regarding assigning a static IP to the ESP, however this was unsuccesful. What i did find out is the following:

        Im using a Fritz Repeater. When the esp32 is working correctly with wifi the funkchannel in the repeater is channel 1. When the esp32 stops working i have checked the channel in the repeater has automatically changed to channel 11.
        In order to solve this issue one should configure the repeater not to change channels automatically. I have read in some forum the ESP’s work ideally with channels < 10.

        I still havent changed the channel but I have come one step closer to the solution.

        thanks for your help

        Reply

Leave a Reply to Lucas Canete Cancel reply

Download our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.