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

13 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
  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

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.