ESP32 Air sensors
One of the easier projects that I've had on the todo pile for a long time was a temperature and humidity sensor to plot a time series in home-assistant. I had ordered the parts back last winter, but they had sat unused in the workshop waiting for a rainy weekend.
Well their time has come, this week I put together a very simple prototype, that measures from the sensor, sends the values over MQTT from the ESP32 to my home server, where the results can be graphed in home assistant.
There are many similar projects floating around the internet, but no complete instructions, so I had to piece things together. I first wasted a morning trying to program the ESP32 from a mac, before remembering that this was a losing battle, and installing Arduino IDE on a Windows machine.
The temperature sensor is a little DHT11 module, but I wasted an afternoon
trying to get a reading before realising the module has built in resistors and
demands to be powered off of the Vin
of the ESP32 rather than the 3.3v pin.
With a 10k pull up resistor to the data pin, everything comes together nicely,
and after testing in a breadboard, I soldered the resistor into a little cable
that fits nicely between the sensor and the 3 pins on one end of the ESP32 DEV
chip.
Then I was onto the software. I wasted yet more time trying to get this to work with the adafruit MQTT library, before giving up and using a different one. Eventually, I got the values into home assistant where I could make a graph.
Air sensor code
#include <DHT.h>
#include "EspMQTTClient.h"
// < INSERT YOUR WIFI AND MQTT SETTINGS... >
#define DHT_SENSOR_PIN 13
#define DHT_SENSOR_TYPE DHT11
DHT dht_sensor(DHT_SENSOR_PIN, DHT_SENSOR_TYPE);
EspMQTTClient client(
WLAN_SSID,
WLAN_PASS,
MQTT_BROKER,
MQTT_USERNAME,
MQTT_PWD,
"livingroom-air-sensor"
);
void setup() {
Serial.begin(9600);
dht_sensor.begin(); // initialize the DHT sensor
client.enableDebuggingMessages();
}
void loop() {
client.loop();
if (client.isConnected()){
float humi = dht_sensor.readHumidity();
float tempC = dht_sensor.readTemperature();
// check whether the reading is successful or not
if (isnan(tempC) || isnan(humi) || tempC < 0.001 || humi < 0.001){
Serial.println("Failed to read from DHT sensor!");
} else {
client.publish(LOCATION + "/temperature", String(tempC));
client.publish(LOCATION + "/humidity", String(humi));
}
delay(10000);
}
}
void onConnectionEstablished() {}
Home assistant config
// Add to configuration.yaml
sensor:
- platform: mqtt
state_topic: 'home/livingroom/temperature'
name: 'Living room temperature'
unit_of_measurement: '°C'
- platform: mqtt
state_topic: 'home/livingroom/humidity'
name: 'Living room humidity'
unit_of_measurement: '%'
Next steps
- Using deep sleep to reduce power by turning off wifi etc. between measurements.
- Powering with battery / solar
- 3D printing a nice case.
- Store wifi creds in EEPROM so changing wifi doesn't require a reflash