Smart Home Temperature and Humidity Monitor Using ESP32 & MQTT
Smart Home Temperature and Humidity Monitor Using ESP32 & MQTT file AtGDCmor6F3Mh8qftVcUYz

Smart Home Temperature and Humidity Monitor Using ESP32 & MQTT

This project uses an ESP32 microcontroller to measure temperature and humidity using a DHT22 sensor. The collected data is sent to an MQTT broker over Wi-Fi, allowing remote monitoring via an MQTT dashboard on a PC or smartphone.


1. Introduction

Real-World Applications:

  • Smart home automation
  • Agricultural monitoring
  • Industrial environment tracking
  • Weather stations

2. Learning Objectives

By completing this project, you will:

  • Learn how to interface the DHT22 sensor with the ESP32.
  • Set up an MQTT broker (e.g., Mosquitto) and publish sensor data.
  • Visualize data on an MQTT dashboard.
  • Gain hands-on experience with ESP32 and IoT cloud connectivity.

3. Components & Tools

Hardware Components:

An ESP32 development board is required as the main controller. The DHT22 sensor is used to measure temperature and humidity. A 10kΩ resistor is necessary as a pull-up for the sensor’s data line. Additional components include a breadboard for easy prototyping, jumper wires for connections, and a USB cable to program the ESP32.

Software & Online Services:

Arduino IDE is used to write and upload the ESP32 program. The MQTT broker, such as Mosquitto or HiveMQ, is needed to handle data transmission. An MQTT dashboard app will be used to monitor the sensor data in real time.


4. Circuit Breakdown

ESP32 to DHT22 Wiring Diagram

The DHT22 sensor requires three connections to the ESP32:

  • The VCC pin of the DHT22 connects to the 3.3V pin of the ESP32 to supply power.
  • The GND pin of the sensor connects to the GND pin of the ESP32.
  • The Data pin of the DHT22 connects to GPIO4 of the ESP32. A 10kΩ pull-up resistor is placed between the VCC and Data pin to ensure stable communication.

5. Programming the ESP32

Required Libraries:

Before programming, install the following libraries in the Arduino IDE:

  • DHT sensor library (DHT.h)
  • PubSubClient library (for MQTT communication)
  • WiFi library (to enable ESP32’s wireless functionality)

Full Source Code:

#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>

// Wi-Fi credentials
const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";

// MQTT Broker details
const char* mqtt_server = "broker.hivemq.com"; // Public broker
const int mqtt_port = 1883;
const char* topic = "home/temperature";

// DHT22 configuration
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

// ESP32 Client
WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
    Serial.begin(115200);
    
    // Connect to Wi-Fi
    WiFi.begin(ssid, password);
    Serial.print("Connecting to WiFi...");
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("\nConnected!");

    // Connect to MQTT
    client.setServer(mqtt_server, mqtt_port);
    while (!client.connected()) {
        Serial.print("Connecting to MQTT...");
        if (client.connect("ESP32Client")) {
            Serial.println("connected!");
        } else {
            Serial.print("failed, rc=");
            Serial.print(client.state());
            Serial.println(" retrying...");
            delay(2000);
        }
    }

    dht.begin();
}

void loop() {
    if (!client.connected()) {
        while (!client.connect("ESP32Client")) {
            Serial.println("Reconnecting to MQTT...");
            delay(2000);
        }
    }

    // Read DHT22 sensor values
    float temperature = dht.readTemperature();
    float humidity = dht.readHumidity();

    if (!isnan(temperature) && !isnan(humidity)) {
        Serial.print("Temperature: ");
        Serial.print(temperature);
        Serial.print("°C, Humidity: ");
        Serial.print(humidity);
        Serial.println("%");

        // Publish MQTT message
        String payload = "{ \"temperature\": " + String(temperature) + ", \"humidity\": " + String(humidity) + " }";
        client.publish(topic, payload.c_str());
    } else {
        Serial.println("Failed to read from DHT sensor!");
    }

    delay(5000); // Send data every 5 seconds
}

6. Setting Up the MQTT Broker

If you don’t have an MQTT broker, install Mosquitto on your PC or Raspberry Pi using the following command:

sudo apt update  
sudo apt install mosquitto mosquitto-clients  

After installation, start the broker with:

mosquitto -v  

To subscribe and monitor the sensor data, use:

mosquitto_sub -h broker.hivemq.com -t "home/temperature" -v  

7. Testing & Debugging

Common Issues & Fixes

If the ESP32 fails to connect to Wi-Fi, verify the SSID and password and ensure the router is within range. For MQTT issues, confirm that the MQTT broker is running and the correct topic and port number are being used. If the sensor readings appear incorrect or return “NaN” values, check the wiring and ensure the pull-up resistor is properly connected. Restarting the ESP32 may also resolve sensor communication issues.

Testing Steps:

  1. Open the Serial Monitor in the Arduino IDE.
  2. Verify that the ESP32 connects to Wi-Fi successfully.
  3. Check if the MQTT connection is established.
  4. Subscribe to the MQTT topic on a PC or mobile app.
  5. Observe the real-time temperature and humidity data.

8. Extensions & Upgrades

There are several ways to enhance this project:

  • Use a different MQTT broker, such as Adafruit IO or ThingsBoard.
  • Add an OLED display to show real-time temperature and humidity.
  • Integrate a relay module to control a fan when the temperature exceeds a threshold.
  • Connect the system with Home Assistant for smart home automation.

9. Conclusion

This project successfully demonstrates how to build an IoT-based temperature and humidity monitoring system using the ESP32 and MQTT. The data collected can be expanded for various applications such as smart home automation, agricultural monitoring, and industrial safety.

Would you like to add data visualization using Node-RED or a web-based dashboard for enhanced monitoring? 🚀