Turning ESP8266 WiFi off to save power (and turn it on later)

There are lot of discussions how to turn ESP8266 WiFi off and on over there. Luckily, the solution is quite straightforward.

// Set WiFi credentials
#define WIFI_SSID "your-wifi-ssid"
#define WIFI_PASS "your-wifi-pass"

void disableWifi(){
    Serial.print(millis());
    Serial.print("\tdisableWifi\t");

    WiFi.disconnect();
    WiFi.mode(WIFI_OFF);
    WiFi.forceSleepBegin();
    yield();

    Serial.println("OK");
}

void enableWifi(){
    Serial.print(millis());
    Serial.print("\tenableWifi");

    WiFi.forceSleepWake();
    yield();
    WiFi.mode(WIFI_STA);
    WiFi.begin(WIFI_SSID, WIFI_PASS);

    while (WiFi.status() != WL_CONNECTED) {
        digitalWrite(LED_BUILTIN, LOW);
        delay(250);
        digitalWrite(LED_BUILTIN, HIGH);
        delay(250);
        Serial.print(".");
    }

    Serial.println(WiFi.localIP());
}

The most useful and in-depth study has been carried out by OppoverBakke. In the first post he studies the power use of ESP8266 and in the second one he suggests the correct order of WiFi.forceSleepWake() and WiFi.mode() calls. The yield() call is required to let ESP ROM to get its internal things straight.

Further references:

Leave a Reply

Your email address will not be published. Required fields are marked *

ninety six − = ninety two