[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:

You may also want to take a look at WiFiMulti. It allows you to register multiple networks (SSID/password combinations). The ESP32 will connect to the Wi-Fi network with the strongest signal (RSSI). If the connection is lost, it will connect to the next network on the list. Read: ESP32 WiFiMulti: Connect to the Strongest Wi-Fi Network (from a list of networks).

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

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 newsletter!

51 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
  8. Getting error in following lines

    WiFi.onEvent(WiFiStationDisconnected, SYSTEM_EVENT_STA_DISCONNECTED);

    no matching function for call to ‘WiFiClass::onEvent(void (&)(arduino_event_id_t, arduino_event_info_t), system_event_id_t)’

    In function ‘void WiFiStationDisconnected(arduino_event_id_t, arduino_event_info_t)’:
    CameraWebServerBluFi:30:23: error: ‘union arduino_event_info_t’ has no member named ‘disconnected’; did you mean ‘eth_connected’?
    Serial.println(info.disconnected.reason);
    ^~~~~~~~~~~~
    eth_connected

    Reply
  9. Getting the WIFI to work reliability is a problem. I have 20 plus esp32’s that I want to deploy to weight, check temperature and humidity on bee hives. I have explained this in other comments. I use a filemanager.h to allow the attachment to a SSID with Password. This works fine and the units get on line OK and attach to an AP point in the field. This runs back to my house via ethernet cable and the 115vac cable from the house. I poll the units every 5min via a Raspberry Pi in to spread sheets (WT, TEMP, HMD;IP). This works great once running (I may have to cycle power to get some units to get on line). The main problem is a power outage at my home when everything goes down. When the power is restored, the esp32’s come back faster than the router and AP’s. I tried to hold up the request to get back on line via a random time Delay in the esp32’s from 30 to 60 sec(30000-60000). It wasn’t long enough(need several mins for network to stabilize. By that time the esp32 hove default to the factory IP 192.168.4.1, and I would have to go to field to use the browser interface on say an Iphone. Setting the delay time in the esp32’s longer is not a good option. If I am redoing SW and uploading I got to wait to see the results on the PC screen. My solution right now is to install a Time Delay After Energization (TDAE) relay. I will provide power to the esp32’s say 10mins after power is restored as the router and AP’s get on line in ~2-3min. Most of the time, when I unplug a esp32, move it and power it on; it comes back up and attaches ok. I also will use a wifi power plug after restart to be able to cycle power via of an APP if some units don’t come back on line. I have yet to get this “cobbled” together to fully check this out. I intend to split the esp32’s in to groups of say 4 to trying to get a restart of all units and not drop another unit. The only other way is this maybe to use a “hard” SSID and PW. Hate to have “20plus unloads” to handle. I am still keeping the random delay timer from 5 to 30 sec so all units are not trying to get on the AP’s at the same time and several TDAE’s set at different times.

    Reply
  10. Had an error like this:
    Wlan.cpp:32:64: error: no matching function for call to ‘WiFiClass::onEvent(void (&)(arduino_event_id_t, arduino_event_info_t), system_event_id_t)’
    WiFi.onEvent(WiFiStationConnected, SYSTEM_EVENT_STA_CONNECTED);

    Had to change the events to start with ‘ARDUINO_EVENT_WIFI_STA_’

    So ‘SYSTEM_EVENT_STA_CONNECTED’ became ‘ARDUINO_EVENT_WIFI_STA_CONNECTED’

    Reply
  11. I have ESP wifi connect to my Router and able transfer data just between tcp connection fine. I power off (disconnect wifi) the router but I don’t get the SYSTEM_EVENT_STA_DISCONNECTED event. Please explain.

    Reply

Leave a Reply to Noushad Olakara 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.