Very Deep Sleep and energy saving on ESP8266 – Part 3: MQTT

In part 1 and 2 of this series, I sketched how to be very energy efficient when using a battery (part 1) and how to periodically gather sensor data and send that to a server through http (part 2).

In this part 3 I will show how to use an energy thrifty ESP8266 sketch to send sensor data via MQTT.

Again I am using the sketch from part 1, that has a section for ‘read data’ or ‘do stuff’  and a section for ‘send data’ and  I just insert the necessary code.

All in all it is quite straight forward. This time I will not be using a BME280 sensor, but that good old DHT11.
As usual, you have to insert your own wifi credentials, and in this case also the ip number and port of your MQTT broker.

I laced the sketch with print statement that should help you in case of problems, but once you have the sketch up and running you can remove those.

There is a possibility for a bit more enerdy saving:
I use the following 2 statements to read and send the sensor data:

client.publish("home/sleep/stat/temp",String(dht.readTemperature()).c_str(),false);
client.publish("sleep/sleep/stat/humid",String(dht.readHumidity()).c_str(),false);

However, the DHT11 isn’t a really fast sensor and the read is while we are connected to WiFi. You could probably shave off a bit of connection time (and thus current) by reading the sensors in the ‘do stuff’ section, store them each into a global variable and use those variables in your MQTT publish.
Do that as follows:

//global
float t;
float h;

//do stuff
t=dht.readTemperature();
h=dht.readHumidity();

//when connected
client.publish("home/sleep/stat/temp",String(t).c_str(),false); client.publish("sleep/sleep/stat/humid",String(h).c_str(),false);

This would also allow you to check for false readings with

if(isnan(h)||isnan(t));

and take corrective action. But that is not really the subject of this HowTo. Don’t forget a 5.1k pull-up resistor. As the DHT11 draws about 0.5mA, you could decide to feed it from one of the gpio pins and just switch it on when needed. (0.5mA comes to 12mAh over a day). However, also take into account that the DHT11 may need a bit of time to get ready.

Also, this sketch only publishes MQTT messages, it does not subscribe to any messages. DeepSleep and receiving subscribed MQTT messages comes with its own set of problems, but it is not impossible. Perhaps that I will write about that in the future.

You will find the link to this program here.

Part 1 -DeepSleep General
Part 2 -DeepSleep HTTP publishing
Part 3 -DeepSleep MQTT Publishing
Part 4 -DeepSleep MQTT Subscribing
Part 5 -DeepSleep ESP-NOW