Will a Script Continue Once You Reconnect to Wif

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:

  • [SOLVED] Reconnect ESP32 to Wi-Fi Network After Lost Connection

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:

  • ESP8266WiFi library Documentation
  • ESP8266 Station Class

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:

  • Build Web Servers with the ESP32/ESP8266 eBook (2nd edition)
  • Home Automation using ESP8266 eBook

We hope you've found this tutorial useful.

Thanks for reading.

macdonaldpown1998.blogspot.com

Source: https://randomnerdtutorials.com/solved-reconnect-esp8266-nodemcu-to-wifi/

0 Response to "Will a Script Continue Once You Reconnect to Wif"

إرسال تعليق

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel