15/08/2019

ESP8266 Modem Sleep with MQTT

By snorlaxprime

Just to finished up with the final post in regards to ESP8266 sleep mode. In the process of learning all the different sleep modes, I stumble across a good post to share the measurements on the different sleep modes, you can check it out here.

To continue the journey from previous post about ESP8266 Deep sleep and ESP8266 Light sleep, the last one is about the Modem sleep. The Modem Sleep is useful when you want to safe some battery, this is done by powering off WiFi only. The code to switch the Wifi OFF and ON the is as below:

WiFi.forceSleepBegin(); // Wifi off 
WiFi.forceSleepWake(); // Wifi on

Hopefully this can be useful to reduce the power consumption when constant Wifi connection is not required. So with slight modification our previous code used to perform the light sleep can be repurposed for this.

Setup() section

The Setup () section only consist of the serial port initialisation as shown in the following code:

void setup() {
   Serial.begin(115200);
   Serial.println();
 }

Loop() section

The loop section is responsible to do the work, this can be shown in the following code:

 void loop() {
   data();
   delay(200);
   Serial.println("Going to sleep now");
   WiFi.forceSleepBegin();  // Wifi Off
   delay(1000*10); // sleep for 10 seconds
   WiFi.forceSleepWake();  // Wifi On
   Serial.println("Wake up");
 }

As you can see the Data() function is responsible to get the temperature sensor reading and posting the result to the MQTT broker. This is explained in details in the next section. We are forcing the Wifi to go to sleep for 10 seconds and then bring it back to life.

Data() function

The data function as explained previously is responsible to read the temperature sensor value. When this is done, because it just woke up from Modem sleep we need to re-initialise the Wifi, this is achieve by calling the initiWifi() function. Then once the Wifi connection is established we are trying to connect to the MQTT broker, this is done by calling the connectMQTT() function. Once we are connected then we publish the temperature to the “/homeautomation/temperature” topic. The code of data() function is shown below:

void data() {
   int value = analogRead(A0);
   float volts=(value * 3.03) / 1024;      //conversion to volts
   tempC = volts*100.0;             //conversion to temp Celsius
   Serial.print("Temperature C: ");
   Serial.println(tempC);
   initWifi();   // init Wifi
   connectMQTT(); // connect to MQTT broker and publish
   if (client.connected()) {
     Serial.println("MQTT client connected");
     client.publish("/homeautomation/temperature", String(tempC));
     delay(1000);
   } else {
     Serial.println("MQTT client not connected");
   }
 }

If you would like the full source code of the above, you can download it from the following location. If you like this post, please drop me a line or let me know if you have any questions.