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

This quick guide shows different ways to reconnect the ESP8266 NodeMCU board to a Wi-Fi network after a lost connection. This can be useful if the ESP8266 temporarily loses the Wi-Fi signal; the ESP8266 is temporarily out of the router’s Wi-Fi range; the router restarts; the router loses internet connection or other situations.

Resolved ESP8266 NodeMCU Reconnect to Wi-Fi After Connection is Lost

We have a similar guide for the ESP32 board:

Reconnect to Wi-Fi Network After Lost Connection

The ESP8266 has the ability to automatically reconnect to your router in case of a Wi-Fi outage. For example, if the ESP8266 is connected to your router and you suddenly turn it off, when it goes back on, the ESP8266 can reconnect automatically. However, many of our readers report situations in which the ESP8266 doesn’t reconnect. In those cases, you can try one of the other next suggestions (continue reading).

To reconnect to Wi-Fi after a connection is lost, you can use WiFi.setAutoReconnect(true); followed by WiFi.persistent(true); to automatically reconnect to the previously connected access point:

WiFi.setAutoReconnect(true);
WiFi.persistent(true);

Add these previous lines right after connecting to your Wi-Fi network. For example:

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());
  WiFi.setAutoReconnect(true);
  WiFi.persistent(true);
}

Here’s a complete example using this method. Every 30 seconds, it prints the Wi-Fi connection status. You can temporarily shut down your router and see the wi-fi status changing. When the router is back on again, it should automatically connect.

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/solved-reconnect-esp8266-nodemcu-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 <ESP8266WiFi.h>

// Replace with your network credentials
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());
  //The ESP8266 tries to reconnect automatically when the connection is lost
  WiFi.setAutoReconnect(true);
  WiFi.persistent(true);
}

void setup() {
  Serial.begin(115200);
  initWiFi();
  Serial.print("RSSI: ");
  Serial.println(WiFi.RSSI());
}

void loop() {
  //print the Wi-Fi status every 30 seconds
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >=interval){
    switch (WiFi.status()){
      case WL_NO_SSID_AVAIL:
        Serial.println("Configured SSID cannot be reached");
        break;
      case WL_CONNECTED:
        Serial.println("Connection successfully established");
        break;
      case WL_CONNECT_FAILED:
        Serial.println("Connection failed");
        break;
    }
    Serial.printf("Connection status: %d\n", WiFi.status());
    Serial.print("RRSI: ");
    Serial.println(WiFi.RSSI());
    previousMillis = currentMillis;
  }
}

View raw code

Another alternative is calling WiFi.disconnect() followed by WiFi.begin(ssid,password) when you notice that the connection was lost (WiFi.status() != WL_CONNECTED)

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

Alternatively, you can also try to restart the ESP8266 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 the 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.begin(YOUR_SSID, YOUR_PASSWORD);
  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-esp8266-nodemcu-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 <ESP8266WiFi.h>

// Replace with your network credentials
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.begin(ssid, password);
    Serial.println(WiFi.localIP());
    //Alternatively, you can restart your board
    //ESP.restart();
    Serial.println(WiFi.RSSI());
    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.

There is also the WiFi.reconnect() function. However, after several tries, we couldn’t make it work. If anyone knows if there is any trick to make it work, please share.

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

ESP8266 NodeMCU Wi-Fi Events

The ESP8266 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:

  • onStationModeGotIP: when the ESP8266 gets to its final step of the connection: getting its network IP address;
  • onStationModeDisconnected: when the ESP8266 is no longer connected to an 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 onStationModeDisconnected event). Here’s a sample code:

/*
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/solved-reconnect-esp8266-nodemcu-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 <ESP8266WiFi.h>

// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

WiFiEventHandler wifiConnectHandler;
WiFiEventHandler wifiDisconnectHandler;

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 onWifiConnect(const WiFiEventStationModeGotIP& event) {
  Serial.println("Connected to Wi-Fi sucessfully.");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
  Serial.println("Disconnected from Wi-Fi, trying to connect...");
  WiFi.disconnect();
  WiFi.begin(ssid, password);
}

void setup() {
  Serial.begin(115200);

  //Register event handlers
  wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
  wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);
   
  initWiFi();
  Serial.print("RRSI: ");
  Serial.println(WiFi.RSSI());
}

void loop() {
  //delay(1000);
}

View raw code

How it Works?

In this example, we’ve added two Wi-Fi events: when the ESP8266 connects and gets an IP address, and when it disconnects.

When the ESP8266 station connects to the access point and gets it IP address (onStationModeGotIP event), the onWifiConnect() function will be called:

wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);

The onWifiConnect() function simply prints that the ESP8266 connected to Wi-fi successfully and prints its local IP address. 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 onWifiConnect(const WiFiEventStationModeGotIP& event) {
  Serial.println("Connected to Wi-Fi sucessfully.");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
}

When the ESP8266 loses the connection with the access point (onStationModeDisconnected event), the onWifiDisconnect() function is called.

wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);

That function prints a message indicating that the connection was lost and tries to reconnect:

void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
  Serial.println("Disconnected from Wi-Fi, trying to connect...");
  WiFi.disconnect();
  WiFi.begin(ssid, password);
}

Wrapping Up

This quick tutorial shows different ways on how you can reconnect your ESP8266 NodeMCU board to a Wi-Fi network after the connection is lost (if it doesn’t do that automatically).

For more information about ESP8266 Wi-Fi functions, we recommend taking a look at the documentation:

One of the best applications of the ESP8266 Wi-Fi capabilities is building web servers. If you want to use the ESP8266 NodeMCU or ESP32 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!

22 thoughts on “[SOLVED] Reconnect ESP8266 NodeMCU to Wi-Fi Network After Lost Connection”

  1. is there something to be carefull when using the ESP.restart function? I notice strange behaviour after entering it to my code.
    The nodemcu restarts but cannot connect some of the times

    Reply
  2. Interesting set of commands, tnx.
    Ourely academic: i think the WiFi.persistent(true); command is the default state, so you could leave it out…….but then again, better make safe.
    (I do always switch it off though in deepsleepmode)

    Reply
  3. If you want to force the WiFi reconnection whenever you want.

    You should use WiFi.reconnect(). However it requires some idle time for system to resume the WiFi connection.

    Here is how to use it.

    unsigned long lastReconnectMillis = 0;

    void loop()
    {

    if(WiFi.status() != WL_CONNECTED && millis() – lastReconnectMillis > 10000 /* 10 seconds idle time is enough*/)
    {
    lastReconnectMillis = millis();
    WiFi.reconnect();
    }

    }

    It clean and clear solution that works in ESP8266 and ESP2.

    Reply
    • Hi Joe.
      I applied
      But where am I going wrong
      Can you check please

      #include <ESP8266WiFi.h>
      unsigned long lastReconnectMillis = 0;

      void loop()
      {

      if(WiFi.status() != WL_CONNECTED && millis() – lastReconnectMillis > 10000 /* 10 seconds idle time is enough*/)
      {
      lastReconnectMillis = millis();
      WiFi.reconnect();
      }

      }

      error expression;
      exit status 1
      extended character – is not valid in an identifier

      Reply
  4. Is there the possibility of trying to reconnect to a second or third network for security?
    I’m having this kind of problem, a dock connection and until it comes back I lose some relevant information.
    If I have a second 4G connection it reconnects to it if the first one goes down

    Reply
  5. Hi,
    Thanks for a very good article.
    I am using Blynk 2.0, can I use the same reconnection examples you show.?
    I think Blynk 2.0 has a buildt in reconnectio, but often it takes one or two hours.

    Reply
    • I don’t know if I have a ‘good’ solution, but I do have a solution that keeps me connected for weeks or months even if my gateway router is rebooted. See my code here:

      https://github.com/bill-orange/MicroPython

      Also note the garbage collection:
      f gc.mem_free() < 102000:
      gc.collect()

      I have found aggressive garbage collection to be helpful.

      Bill

      Reply
  6. Guys, good night !

    I have 5 NodeMCU’s and they all no longer connect to my main Wifi network (VIVO-A7CD).
    I made the flash of all erasing everything else they persist in not connecting to this network.
    I erased the flash with several apps and also on the command line in Python.
    (C:\Python27\Scripts>esptool.py –port COM6 –baud 115200 erase_flash)
    But, they connect to another Wifi network (DeusTaVendo).
    I’ve already changed the name of the main network on the VIVO router, but it still gives the same problem.

    It’s not an antenna problem on the boards because the DeusTaVendo Wifi network is far from the boards.
    Previously I used these cards to test with EEPROM, where I stored variables.
    I uploaded a code to reset the EEPROM… but it didn’t fix the problem.

    #include <EEPROM.h>
    void setup() {
    EEPROM.begin(512);
    // write a 0 to all 512 bytes of the EEPROM
    for (int i = 0; i < 512; i++) {
    EEPROM.write(i, 0);
    }
    EEPROM.end();
    }
    void loop() {
    }

    And I did tests with SIPFFS too.
    I uploaded the WifiManager for the boards and saw that it had the SSID / PASS of a network that I had here.
    I uploaded uncommenting the line where ZERAL the wifi networks stored on the card.
    OK. Reset !
    But it didn’t fix the problem.
    It continued not connecting to VIVO-A7CD and connecting to DeusTaVendo.
    I really don’t know what else to do !
    This wifi network has always worked. There was never any problem and now this. I don’t really know what else to do. It may be something I’m not seeing anymore, I see how this could be happening.
    Anyone who knows a solution to this please respond.
    Thanks !!

    TAKE A LOOK AT THE PRINTS…

    SimpleAuthentication (Examples > ESP8266WebServer)

    https://drive.google.com/file/d/1DxwHsLLpe4ks_dsOIE9RU3IUJTr1FVHE/view?usp=sharing

    https://drive.google.com/file/d/1eCwgt72x3-MAizvUflPpyqejBhBHoimU/view?usp=sharing

    https://drive.google.com/file/d/1odSvcj2xM1Kz9y3sioulHREicxHXzqPi/view?usp=sharing

    Reply
  7. I tried the onDisconnect handler and it worked, but I found there were a lot of additional repeat disconnect events during the subsequent attempt to re-connect. For my application, doing a WiFi.status() check in the loop worked out best. It doesn’t have much overhead.

    Also, it’s worth noting that there seems to be restrictions on what can be in the event handler code. This makes sense since handlers should be as short as possible. For example, don’t call delay() in an event handler – it won’t work.

    Reply
  8. Disconnect/connect seem to be working ok for me. The main issue I’m having right now is with the ESP8266 NodeMCU rebooting itself during periods of poor signal and/or interference. I suspect this is an issue with the TCP stack, but am not certain because it only happens to the field unit. I ordered a Wifi jammer to see if I can duplicate the poor signal conditions with my desktop dev unit.

    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.