Smart Home Temperature Monitoring with ESP32
Build a complete WiFi-enabled temperature and humidity monitoring system using ESP32, DHT22 sensor, and MQTT. Includes dashboard setup and mobile alerts.
Table of Contents
1. Project Overview
In this comprehensive guide, we'll build a complete smart home temperature and humidity monitoring system from scratch. This project demonstrates end-to-end IoT implementation, covering hardware assembly, firmware development, cloud connectivity, and user interface creation.
- ESP32 microcontroller programming
- DHT22 sensor interfacing
- MQTT protocol implementation
- Home Assistant integration
- Node-RED dashboard creation
- Mobile notification setup
By the end of this tutorial, you'll have a fully functional monitoring system that:
- Measures temperature and humidity every 10 seconds
- Publishes data to an MQTT broker
- Displays real-time graphs on a dashboard
- Sends mobile alerts when thresholds are exceeded
- Logs historical data for analysis
2. Required Components
The DHT22 sensor has a slow response time (2 seconds). Don't poll it more frequently than once every 2 seconds to avoid reading errors.
3. Hardware Setup
Follow this wiring diagram:
- DHT22 VCC → ESP32 3.3V
- DHT22 GND → ESP32 GND
- DHT22 DATA → ESP32 GPIO 4
- 10k Resistor → Between VCC and DATA pin (pull-up)
DHT22 Pinout (Front View):
┌─────────────┐
│ ● ● ● ● │
│ 1 2 3 4 │
└─────────────┘
Pin 1: VCC (3.3V)
Pin 2: DATA (GPIO 4)
Pin 3: NC (Not Connected)
Pin 4: GND
4. Software Installation
Download and install Arduino IDE from the official website.
In Arduino IDE:
- Go to
File → Preferences - Add this URL to "Additional Board Manager URLs":
https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json - Go to
Tools → Board → Boards Manager - Search for "ESP32" and install "esp32 by Espressif Systems"
Go to Sketch → Include Library → Manage Libraries and install:
- DHT sensor library by Adafruit
- Adafruit Unified Sensor
- PubSubClient by Nick O'Leary (MQTT)
5. ESP32 Programming
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
// WiFi credentials
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";
// MQTT Broker settings
const char* mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883;
const char* mqtt_user = "";
const char* mqtt_password = "";
// DHT Sensor
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
WiFiClient espClient;
PubSubClient client(espClient);
// MQTT Topics
const char* temperature_topic = "home/livingroom/temperature";
const char* humidity_topic = "home/livingroom/humidity";
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP32Client-";
clientId += String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
dht.begin();
setup_wifi();
client.setServer(mqtt_server, mqtt_port);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Read sensor data
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();
if (isnan(humidity) || isnan(temperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Publish to MQTT
char tempString[8];
char humString[8];
dtostrf(temperature, 1, 2, tempString);
dtostrf(humidity, 1, 2, humString);
client.publish(temperature_topic, tempString);
client.publish(humidity_topic, humString);
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.print("°C, Humidity: ");
Serial.print(humidity);
Serial.println("%");
delay(10000); // Wait 10 seconds
}
6. MQTT Broker Setup
For this project, we'll use a public MQTT broker for testing. For production, consider setting up your own:
# Install Mosquitto on Ubuntu/Raspberry Pi
sudo apt update
sudo apt install mosquitto mosquitto-clients
# Start Mosquitto
sudo systemctl start mosquitto
sudo systemctl enable mosquitto
# Test subscription
mosquitto_sub -h localhost -t "home/#" -v
7. Dashboard Configuration
Option 1: Node-RED Dashboard
# Install Node-RED
bash <(curl -sL https://raw.githubusercontent.com/node-red/linux-installers/master/deb/update-nodejs-and-nodered)
# Access dashboard at http://your-ip:1880/ui
Import this flow into Node-RED:
[
{
"id": "mqtt-in",
"type": "mqtt in",
"name": "Temperature",
"topic": "home/livingroom/temperature",
"broker": "mqtt-broker"
},
{
"id": "gauge",
"type": "ui_gauge",
"name": "Temp Gauge",
"group": "dashboard-group",
"range": {"min": 0, "max": 50},
"format": "{{value}}°C"
}
]
Option 2: Home Assistant
Add to your configuration.yaml:
mqtt:
sensor:
- name: "Living Room Temperature"
state_topic: "home/livingroom/temperature"
unit_of_measurement: "°C"
device_class: "temperature"
- name: "Living Room Humidity"
state_topic: "home/livingroom/humidity"
unit_of_measurement: "%"
device_class: "humidity"
8. Mobile Alerts Setup
Use Node-RED to send push notifications:
// Install node-red-contrib-pushover
// Create Pushover account at https://pushover.net/
[
{
"id": "function",
"type": "function",
"name": "Check Threshold",
"func": "if (msg.payload > 30) {\n msg.payload = {\n message: \"High temperature alert! Current: \" + msg.payload + \"°C\",\n title: \"Temperature Alert\",\n priority: 1\n };\n return msg;\n} else {\n return null;\n}"
},
{
"id": "pushover",
"type": "pushover",
"name": "Send Alert"
}
]
9. Testing & Calibration
- Upload Code: Upload the ESP32 code and open Serial Monitor (115200 baud)
- Verify WiFi: Check that ESP32 connects to WiFi
- Test MQTT: Subscribe to topics and verify data publication
- Dashboard Check: Ensure dashboard displays real-time values
- Alert Test: Use a heat source to trigger temperature alerts
Compare readings with a calibrated thermometer. Add offset in code if needed:
temperature = temperature + 1.5;
10. Troubleshooting
Problem: DHT22 Reading Errors
- Check wiring connections
- Ensure 10k pull-up resistor is connected
- Verify power supply (3.3V, not 5V)
- Increase delay between readings
Problem: WiFi Connection Fails
- Verify SSID and password
- Check 2.4GHz vs 5GHz (ESP32 only supports 2.4GHz)
- Move closer to router
- Check router MAC filtering
Problem: MQTT Not Connecting
- Verify broker address and port
- Check firewall settings (port 1883)
- Test with MQTT client (MQTTX)
- Verify broker is running
Next Steps
Congratulations! You've built a complete IoT monitoring system. Here are ideas to expand:
- Add multiple sensors for different rooms
- Integrate with smart thermostats
- Create historical data logging with InfluxDB
- Add voice control with Alexa/Google Home
- Build a weather prediction algorithm
Related Articles:
Smart Lighting with Alexa & Google Home |
MQTT Protocol: Complete Guide