This fast article demonstrates several ways to reconnect the ESP8266 NodeMCU board to a Wi-Fi network once a connection has been lost. This may be useful if the ESP8266 temporarily loses the Wi-Fi signal; the ESP8266 is temporarily out of range of the router's Wi-Fi; the router restarts; the router loses an internet connection or in other scenarios.
We have a similar guide for the ESP32 board:
Reconnect to Wi-Fi Network After Lost Connection
In the case of a Wi-Fi outage, the ESP8266 can automatically reconnect to your router. For example, if the ESP8266 is connected to your router and you suddenly turn it off, the ESP8266 may reconnect automatically when it is turned back on. However, many of our users have reported situations in which the ESP8266 does not reconnect. In certain cases, try one of the other suggestions (keep 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);
}
Using this method, here is a full example. It prints the Wi-Fi connection status every 30 seconds. You may temporarily shut down your router and see a change in the wireless network status. It ought to connect automatically after turning the router back on.
/*
LEDEdit PRO
Complete project details at https://lededitpro.com/resolve-reconnect-esp8266-to-wi-fi-network/
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;
}
}
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);
When the connection is lost, you may try to restart the ESP8266 using ESP.restart()
.
You can add something like the snippet below 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 interval
and previousMillis
variables. The interval
corresponds to the period between each check-in milliseconds (for example 30 seconds):
unsigned long previousMillis = 0;
unsigned long interval = 30000;
Here’s a complete example.
/*
LEDEdit PRO
Complete project details at https://lededitpro.com/resolve-reconnect-esp8266-to-wi-fi-network/
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;
}
}
This example shows how to connect to a network and checks that it is still connected every 30 seconds. If not, it disconnects and tries to reconnect.
The WiFi.reconnect()
function is also available. We couldn't make it function after multiple tries. If anybody knows of a trick to making it work, please share.
You can also use Wi-Fi Events to detect a lost connection and invoke a function to handle what to do when that happens (see the next section).
ESP8266 NodeMCU Wi-Fi Events
The ESP8266 can handle different Wi-Fi events. Wi-Fi events eliminate the need to continually check the Wi-Fi state. The associated handling function is automatically called when a given event happens.
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 might be useful to identify when a connection has been lost and try to reconnect right away (using the onStationModeDisconnected
event). Here is some sample code:
/*
LEDEdit PRO
Complete project details at https://lededitpro.com/resolve-reconnect-esp8266-to-wi-fi-network/
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);
}
How does it work?
Two Wi-Fi events have been added in this example: when the ESP8266 connects and receives an IP address, and when it disconnects.
Two Wi-Fi events have been added in this example: when the ESP8266 connects and receives an IP address, and when it disconnects.
The onWifiConnect()
function is called when the ESP8266 station connects to the access point and obtains its IP address (onStationModeGotIP
event):
wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
The onWifiConnect()
function simply prints the ESP8266's local IP address and confirms that it is successfully connected to Wi-Fi. To do any other task (such as turning on an LED to show that it is connected to the network successfully), you may modify the function.
void onWifiConnect(const WiFiEventStationModeGotIP& event) {
Serial.println("Connected to Wi-Fi sucessfully.");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
The onWifiDisconnect()
function is triggered when the ESP8266 loses connection with the access point (onStationModeDisconnected
event).
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);
}
Conclusion
This quick tutorial shows several ways to reconnect your ESP8266 to Wi-Fi network after the connection has been lost (if it does not do so automatically).
For more information about ESP8266 Wi-Fi functions, we recommend taking a look at the documentation:
If you like ESP8266, you may also like:
- ESP8266 NodeMCU Deep Sleep with Arduino IDE
- Build a Water Level Control System Using ESP8266 NodeMCU
- Getting Started with ESP8266 NodeMCU Board | Complete Guide
- How to Post on Twitter using an ESP8266
We hope you find this tutorial useful. Thanks for reading