Back to IoT Blog
Smart Home 15 min read Updated: March 2025

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.

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.

What You'll Learn:
  • 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:

2. Required Components

ESP32 Development Board ESP32-WROOM-32 or similar with WiFi
DHT22 Sensor Temperature & Humidity (-40°C to 80°C)
10kΩ Resistor Pull-up resistor for data line
Breadboard For prototyping connections
Jumper Wires Male-to-male and male-to-female
USB Cable Micro-USB for programming
⚠️ Important:

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

1 Connect DHT22 to ESP32

Follow this wiring diagram:

  • DHT22 VCCESP32 3.3V
  • DHT22 GNDESP32 GND
  • DHT22 DATAESP32 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

2 Install Arduino IDE

Download and install Arduino IDE from the official website.

3 Add ESP32 Board Support

In Arduino IDE:

  1. Go to File → Preferences
  2. Add this URL to "Additional Board Manager URLs":
    https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json
  3. Go to Tools → Board → Boards Manager
  4. Search for "ESP32" and install "esp32 by Espressif Systems"
4 Install Required Libraries

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:

Testing: HiveMQ Public Broker broker.hivemq.com:1883 (No auth)
Self-hosted: Mosquitto Install on Raspberry Pi or server
Cloud: AWS IoT Core Managed service with security

# 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

  1. Upload Code: Upload the ESP32 code and open Serial Monitor (115200 baud)
  2. Verify WiFi: Check that ESP32 connects to WiFi
  3. Test MQTT: Subscribe to topics and verify data publication
  4. Dashboard Check: Ensure dashboard displays real-time values
  5. Alert Test: Use a heat source to trigger temperature alerts
💡 Calibration Tip:

Compare readings with a calibrated thermometer. Add offset in code if needed: temperature = temperature + 1.5;

10. Troubleshooting

Problem: DHT22 Reading Errors

Problem: WiFi Connection Fails

Problem: MQTT Not Connecting

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