Your new topic does not fit any of the above??? Check first. Then post here. Thanks.

Moderator: igrr

User avatar
By daveb1014
#52528 OK I have done some testing, and I think I have a solution.

This sketch will connect successfully to wifi, but will fail to connect after you take wifi away for some minutes and put it back (say, when the ESP8266 is taken out of range, which is how I've been testing):

Code: Select all#include <ESP8266WiFi.h>
const int WIFI_TIMEOUT = 10;// 10 seconds
void setup() {
   Serial.begin(115200);
   WiFi.persistent(false);// disables flash config sector overwrite every reset (see https://github.com/esp8266/Arduino/issues/1054) - affects storage of ssid and key
// ***********************************************************
   WiFi.mode(WIFI_STA);// set station/client mode
   WiFi.begin("myssid", "key");// connect to wifi AP

   Serial.println("Awake, attempting to connect to WiFi.");
   int i = 0;
   while (WiFi.status() != WL_CONNECTED) {
      delay(100);// sleep for 100ms
      Serial.print(".");
      i++;
      if (i >= WIFI_TIMEOUT*10) {// connection timed out
         Serial.println("Failed to establish wifi connection. Sleeping.");
         ESP.deepSleep(30000000, RF_DEFAULT);// sleep for 30 seconds and reset
      }
   }
   Serial.println("Connection successfully established ***");
}

void loop() {
   // do some stuff
   Serial.println("Main loop, sleeping now...");
   ESP.deepSleep(30000000, RF_DEFAULT);// sleep for 30 seconds and reset
}


Replacing the // ****************** line with:

Code: Select allWiFi.forceSleepWake();


...fixes the issue. I can now take the ESP8266 out of range of the wifi for some time (I tested with about an hour), and when I return it, it will successfully reconnect.

All of these tests have been done with the ESP8266 running on battery, so that it is never actually power-cycled - even though in the sketches there is a deepSleep and subsequent soft reset, previously I had to power-cycle it to get it to reconnect to wifi.

I think this works. This was a deal-breaker for my IoT projects; I need them to be able to reconnect after wifi goes away and comes back, and I was beginning to think I wouldn't find a software solution!