# ESP8266NodeMCU - how to restart wifi after a disconnect

**URL:** <https://forum.arduino.cc/t/esp8266nodemcu-how-to-restart-wifi-after-a-disconnect/681066>\
**Category:** General Guidance\
**Created:** [November 2, 2020, 5:29pm UTC](https://forum.arduino.cc/t/esp8266nodemcu-how-to-restart-wifi-after-a-disconnect/681066 "2020-11-02T17:29:45Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![johnerrington](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/johnerrington/32/340106_2.png) [@johnerrington](https://forum.arduino.cc/u/johnerrington)\
**Post date:** [November 2, 2020, 5:29pm UTC](https://forum.arduino.cc/t/esp8266nodemcu-how-to-restart-wifi-after-a-disconnect/681066/1 "2020-11-02T17:29:45Z")

</div>

I have a Lolin NodeMCU set up to repeatedly ping devices on my local network, and on the web.  
It uses the ESP8266WiFi library.

Until there is a disconnect it works fine; however I cant see how to get it to reconnect.

[The full project is described here](http://www.skillbank.co.uk/arduino/pinglogger.htm)

and the relevant bits of the sketch - I've attached the full sketch below for context but its quite big.

```cpp
#include <ESP8266WiFi.h>            //WiFi functions

..

WiFiEventHandler gotIpEventHandler, disconnectedEventHandler;

..

```

and in setup()

```cpp
 //monitor Wifi connection and handle D0

  gotIpEventHandler = WiFi.onStationModeGotIP([](const WiFiEventStationModeGotIP & event)
  {
    Serial.print("Station connected, IP: ");
    Serial.println(WiFi.localIP());
    digitalWrite(dPin[1], 0); //blue LED
  });

  disconnectedEventHandler = WiFi.onStationModeDisconnected([](const WiFiEventStationModeDisconnected & event)
  {
    Serial.println("Station disconnected");
    digitalWrite(dPin[1], 1); //blue LED
  });

  bool stationConnected = WiFi.begin(ssid, pass);
  delay(200); //allow time to connect
  // Wait until connection completed
  Serial.print("Connecting to AP...");
  while (WiFi.status() != WL_CONNECTED)  {
    delay(200);
    Serial.print(".");
  }
  Serial.println("Ok\n");
  digitalWrite(dPin[0], 0); //indicate wifi connected -  white LED

```

I've googled & read the documentation but to me its advanced gobbledegook.

[netmonitor-good.ino](https://forum.arduino.cc/uploads/short-url/xOscot7vhgGCibwIfHQawWkqEYJ.ino) (18.2 KB)

---

<div class="post-metadata">

**Author:** ![Railroader](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/railroader/32/274550_2.png) [@Railroader](https://forum.arduino.cc/u/Railroader)\
**Post date:** [November 2, 2020, 5:35pm UTC](https://forum.arduino.cc/t/esp8266nodemcu-how-to-restart-wifi-after-a-disconnect/681066/2 "2020-11-02T17:35:32Z")

</div>

Put the code starting the Wifi in a function of its own. Call that function from setup but also from the code, in loop, where the failure is detected.

---

<div class="post-metadata">

**Author:** ![johnerrington](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/johnerrington/32/340106_2.png) [@johnerrington](https://forum.arduino.cc/u/johnerrington)\
**Post date:** [November 2, 2020, 6:09pm UTC](https://forum.arduino.cc/t/esp8266nodemcu-how-to-restart-wifi-after-a-disconnect/681066/3 "2020-11-02T18:09:20Z")

</div>

Thanks RailRoader, AFAIK the failure is detected by the disconnectedEventHandler - not in the loop().

---

<div class="post-metadata">

**Author:** ![Idahowalker](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/idahowalker/32/238858_2.png) [@Idahowalker](https://forum.arduino.cc/u/Idahowalker)\
**Post date:** [November 2, 2020, 6:13pm UTC](https://forum.arduino.cc/t/esp8266nodemcu-how-to-restart-wifi-after-a-disconnect/681066/4 "2020-11-02T18:13:09Z")

</div>

Here's a code that I use to maintain a WiFi and MQTT connection, perhaps it will give a few hints.

Also, if you have the ESP8266 with OS you can set the keep alive as a separate task.

```cpp
void MQTTkeepalive( void *pvParameters )
{
  // setting must be set before a mqtt connection is made
  MQTTclient.setKeepAlive( 90 ); // setting keep alive to 90 seconds makes for a very realiable connection, must be set before the 1st connection is made.
  for (;;)
  {
    //check for a is connected and if the WiFi thinks its connected, found checking on both is more reliable than just a single check
    if ( (wifiClient.connected()) && (WiFi.status() == WL_CONNECTED) )
    {
      xSemaphoreTake( sema_MQTT_KeepAlive, portMAX_DELAY ); // whiles loop() is running no other mqtt operations should be in process
      MQTTclient.loop();
      xSemaphoreGive( sema_MQTT_KeepAlive );
    }
    else {
      log_i( "MQTT keep alive found MQTT status %s WiFi status %s", String(wifiClient.connected()), String(WiFi.status()) );
      if ( !(WiFi.status() == WL_CONNECTED) )
      {
        connectToWiFi();
      }
      connectToMQTT();
    }
    vTaskDelay( 250 ); //task runs approx every 250 mS
  }
  vTaskDelete ( NULL );
}

```

You can have your WiFi feedback routine either try a reconnect or a reset of the ESP8266 to start all over.

Also, you might want to issue a WiFi.disconnect(); before making the connection:  
As shown below:

```cpp
void connectToWiFi()
{
  byte mac[6];
  log_i( "connect to wifi" );
  while ( WiFi.status() != WL_CONNECTED )
  {
    WiFi.disconnect();
    WiFi.begin( SSID, PASSWORD );
    log_i(" waiting on wifi connection" );
    vTaskDelay( 4000 );
  }
  log_i( "Connected to WiFi" );
  WiFi.macAddress(mac);
  log_i( "mac address %d.%d.%d.%d.%d", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]  );
  WiFi.onEvent( WiFiEvent );
  GetTheTime();
  printLocalTime();
}

```

---

<div class="post-metadata">

**Author:** ![Railroader](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/railroader/32/274550_2.png) [@Railroader](https://forum.arduino.cc/u/Railroader)\
**Post date:** [November 2, 2020, 6:21pm UTC](https://forum.arduino.cc/t/esp8266nodemcu-how-to-restart-wifi-after-a-disconnect/681066/5 "2020-11-02T18:21:02Z")

</div>

> johnerrington:  
> Thanks RailRoader, AFAIK the failure is detected by the disconnectedEventHandler - not in the loop().

Call a restart from there then?

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [May 5, 2021, 7:21pm UTC](https://forum.arduino.cc/t/esp8266nodemcu-how-to-restart-wifi-after-a-disconnect/681066/6 "2021-05-05T19:21:21Z")

</div>

Closed on May 5, 2021, 7:21pm UTC


