Search code examples
c++arduinoesp8266

ESP8266 WiFi Manager and Modem Sleep


Noob question, I'm very knew here, I'm trying tu use wifi manager and modem sleep, but once I turn off the wifi I can't reconnect again. I know what I'm missing is the configuration to connect to the wifi after it has been turned off but I don't know how to do it if I'm using WiFi Manager.

These are the steps:

  1. Power on ESP8266
  2. Call WiFi Manager and set the credential. Save them for the next time
  3. Turn the WiFi Off (In order to collect data from a sensor without power consumption)
  4. Collected my 5 data I need to power on the WiFi and connect to it

I made two functions, one to turn off wifi and one to turn it on

void active_mode(){
  //se spento accendiamo il wifi 
  if(WiFi.status() != WL_CONNECTED){
    WiFi.forceSleepWake();
    
    //here I should connect to the wifi but how
    //if I'm using wifi manager?
    //normally I would use this:
    //WiFi.mode(WIFI_STA);
    //WiFi.begin(ssid, password);
    //but what if I already saved my credential the first time I powered on the esp 
    //how to retrieve them in order to connect to wifi?
    
    delay(1);
  }
}

void sleep_mode(){
  //spegniamo il wifi
  WiFi.disconnect();
  WiFi.forceSleepBegin();
  if(WiFi.status() != WL_CONNECTED){
    Serial.print(WiFi.status());
    Serial.println(" :WiFi spento");
  }
  delay(1);
}

in the void setup I've got this. This way when I first power on my esp I can save my WiFi credential and connect to it everytime I power on my esp.

void setup(){
  // WiFiManager
  // Local intialization.
  WiFiManager wifiManager;

  //wifiManager.autoConnect("AutoConnectAP");
  // if you get here you have connected to the WiFi
  Serial.println("Connected.");
  delay(5000);

  //I call sleep_mode here because I need to collect data from a sensor without the WiFi 
  powered on
  sleep_mode();
}

Here's the loop

void loop() {
 
  //Reading data every 3 seconds and save them in file.txt
  now = millis();    
  if (now - start_time >= timer_save){ 
    //if (count < 3){   
      read_data();
      saveHistory();
      start_time = now;
      count++; 
    //}
  }
     
  //saved 5 data turn on wifi, read them and clear the content of file.txt
  if (count == 5){
    active_mode();
    // checking connection
    if (!client.connected()) {
            reconnect();
          }
    client.loop();
    readHistory();
    //mqtt_publish();
    LittleFS.remove("/file.txt");
    count = 0;
    start_time = 0;
    sleep_mode();
    //delay(5000);
  }

}//end of void loop();

Solution

  • if I've understood the question right. This could be of great help: https://github.com/tzapu/WiFiManager/issues/272 If not, my bad.