Smart Room Temperature Monitor Using ESP32, DHT22, MQTT, and Node-RED

Smart Room Temperature Monitor Using ESP32, DHT22, MQTT and Node-RED

Smart Room Temperature Monitor Using ESP32, DHT22, MQTT and Node-RED

Introduction

Learning MQTT concepts is important, but the real fun begins when you start building practical IoT projects.

One of the most common beginner IoT projects is a Smart Room Temperature Monitor. It combines sensors, wireless communication, dashboards, and real-time monitoring into a single project that’s both useful and easy to understand.

In this project, we’ll use an ESP32 and a DHT22 temperature and humidity sensor to collect environmental data. The ESP32 will publish the readings to an MQTT broker running Mosquitto, and Node-RED will display the data on a live dashboard.

By the end of this tutorial, you’ll have a complete IoT monitoring system that can be expanded into smart home automation, weather stations, greenhouse monitoring, and industrial IoT applications.

This project also helps you understand how the different technologies you’ve learned so far work together in a real-world scenario.

Project Overview

The system works as follows:

  1. DHT22 measures temperature and humidity.
  2. ESP32 reads the sensor values.
  3. ESP32 publishes the readings using MQTT.
  4. Mosquitto broker receives the messages.
  5. Node-RED subscribes to the MQTT topics.
  6. Dashboard displays real-time sensor data.

What You Will Learn

In this project, you’ll learn:

  • Interfacing DHT22 with ESP32
  • Reading temperature and humidity values
  • Publishing MQTT messages from ESP32
  • Using Mosquitto MQTT Broker
  • Building a Node-RED Dashboard
  • Visualizing sensor data in real time
  • Creating a complete IoT monitoring solution

Components Required

Hardware

  • ESP32 Development Board
  • DHT22 Temperature and Humidity Sensor
  • Breadboard
  • Jumper Wires
  • USB Cable

Software

  • Arduino IDE
  • Mosquitto MQTT Broker
  • Node-RED
  • MQTT Explorer (Optional)

Understanding the System Architecture

The complete communication flow is shown below:

Smart Room Temperature Monitor Using ESP32, DHT22, MQTT, and Node-RED

The ESP32 acts as the MQTT Publisher, while Node-RED acts as the Subscriber.

Why Use DHT22?

The DHT22 is one of the most popular sensors for beginner IoT projects.

Smart Room Temperature Monitor Using ESP32, DHT22, MQTT, and Node-RED

Benefits include:

  • Measures temperature and humidity
  • Good accuracy
  • Low cost
  • Easy to interface with ESP32
  • Large community support

Typical measurement range:

Temperature: -40°C to 80°C
Humidity: 0% to 100%

Wiring Diagram

Connect the DHT22 sensor to the ESP32 as follows:

DHT22 Pin ESP32 Pin
VCC 3.3V
DATA GPIO4
GND GND

If you’re using a bare DHT22 sensor, add a 10kΩ pull-up resistor between VCC and DATA.

Install Required Libraries

Open Arduino IDE and install the following libraries:

DHT Sensor Library

Library Manager: DHT sensor library by Adafruit

Adafruit Unified Sensor

Library Manager: Adafruit Unified Sensor

PubSubClient

Library Manager: PubSubClient by Nick O'Leary

These libraries simplify sensor reading and MQTT communication.

MQTT Topics Used

We’ll create separate topics for temperature and humidity.

Temperature Topic

home/room/temperature

Humidity Topic

home/room/humidity

Using separate topics makes dashboard design easier and improves scalability.

ESP32 Program

Copy paste the below code and paste it in Arduino IDE.

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

// Wi-Fi Credentials
const char* ssid = “YOUR_WIFI_NAME”;
const char* password = “YOUR_WIFI_PASSWORD”;

// MQTT Broker IP Address
const char* mqtt_server = “192.168.1.150”;

// MQTT Topics
const char* tempTopic = “home/room/temperature”;
const char* humTopic = “home/room/humidity”;

// DHT22 Configuration
#define DHTPIN 4
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

WiFiClient espClient;
PubSubClient client(espClient);

unsigned long lastMsg = 0;

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.print(“IP Address: “);
Serial.println(WiFi.localIP());
}

void reconnect() {

while (!client.connected()) {

Serial.print(“Connecting to MQTT Broker…”);

String clientId = “ESP32TempMonitor-“;
clientId += String(random(0xffff), HEX);

if (client.connect(clientId.c_str())) {

Serial.println(“Connected”);

} else {

Serial.print(“Failed, rc=”);
Serial.print(client.state());
Serial.println(” Retrying in 5 seconds”);

delay(5000);
}
}
}

void setup() {

Serial.begin(115200);

dht.begin();

setup_wifi();

client.setServer(mqtt_server, 1883);
}

void loop() {

if (!client.connected()) {
reconnect();
}

client.loop();

unsigned long now = millis();

if (now – lastMsg > 5000) {

lastMsg = now;

float temperature = dht.readTemperature();
float humidity = dht.readHumidity();

if (isnan(temperature) || isnan(humidity)) {

Serial.println(“Failed to read from DHT22”);
return;
}

char tempString[8];
dtostrf(temperature, 1, 2, tempString);

char humString[8];
dtostrf(humidity, 1, 2, humString);

client.publish(tempTopic, tempString);
client.publish(humTopic, humString);

Serial.print(“Temperature: “);
Serial.print(tempString);
Serial.println(” °C”);

Serial.print(“Humidity: “);
Serial.print(humString);
Serial.println(” %”);
}
}

Wi-Fi Credentials

Update your Wi-Fi settings:

const char* ssid = "YOUR_WIFI";
const char* password = "YOUR_PASSWORD";

Configure the MQTT Broker

Before uploading the code, you need to tell the ESP32 where your MQTT broker is running.

There are two common options:

Option 1: Raspberry Pi Running Mosquitto

If you’ve followed our Raspberry Pi MQTT Broker Setup Using Mosquitto tutorial, use the IP address of your Raspberry Pi as the MQTT broker address.

To find your Raspberry Pi’s IP address, open a terminal and run:

hostname -I

Example output:

192.168.29.142

Update the MQTT broker address in your ESP32 code:

const char* mqtt_server = "192.168.29.142";

Note: Make sure your ESP32 and Raspberry Pi are connected to the same Wi-Fi network so they can communicate with each other.

Option 2: Use a Public MQTT Broker

If you don’t have a Raspberry Pi or a local MQTT broker yet, you can use a free public MQTT broker for testing and learning purposes.

Some popular public MQTT brokers are:

MQTT Broker

Address

Port

HiveMQ Public Broker

broker.hivemq.com

1883

Eclipse Mosquitto Test Broker

test.mosquitto.org

1883

EMQX Public Broker

broker.emqx.io

1883

For example, if you’re using the HiveMQ public broker, update your code as follows: const char* mqtt_server = “broker.hivemq.com”;

Note: Public MQTT brokers are designed for testing and educational purposes. Since anyone can publish or subscribe to topics on these brokers, avoid sending sensitive or personal information. For real-world or production IoT projects, it’s recommended to use your own MQTT broker (such as Mosquitto on a Raspberry Pi) with authentication and TLS encryption enabled.

Publish Sensor Data

The ESP32 will:

  • Read temperature
  • Read humidity
  • Publish readings every few seconds

Example MQTT payload:

Temperature: 28.5
Humidity: 65

Testing MQTT Messages

Before creating the dashboard, verify that data is reaching the broker.

Subscribe to the temperature topic:

mosquitto_sub -h localhost -t home/room/temperature

Subscribe to humidity:

mosquitto_sub -h localhost -t home/room/humidity

If everything is working correctly, you should see sensor readings appearing every few seconds.

Example:
28.5
28.6
28.7

Creating the Node-RED Dashboard

Now it’s time to visualize the data.

Open Node-RED:

http://<RaspberryPi-IP>:1880

Add MQTT Input Nodes

Create two MQTT Input nodes. Open it and click on + Icon

For MQTT IN Temperature node add

Topic: home/room/temperature

For MQTT IN Humidity node add

Topic: home/room/humidity

Now add details below to create the node you can add any relevant name you want. For reference add below details

Name: Any relevant name you want

Server: IP address or name of MQTT broker

Smart Room Temperature Monitor Using ESP32, DHT22, MQTT and Node-RED


Add Dashboard Gauge Nodes

Drag two Gauge widgets from the dashboard section.

Temperature Gauge

Label: Temperature

Unit: °C

Range: 0 – 100

Humidity Gauge

Label: Humidity 

Unit: %

Range: 0 – 50

Connect the Nodes

Now that you’ve added the MQTT Input nodes and Dashboard Gauge nodes, it’s time to connect them so the sensor readings can be displayed on the dashboard.

Create two separate flows:

Flow 1 – Temperature Monitoring

Connect the MQTT Input node (Temperature) to the Dashboard Gauge node (Temperature).

MQTT Input (Temperature) --> Dashboard Gauge

This flow receives the temperature values published by the ESP32 and displays them on a dashboard gauge.

Flow 2 – Humidity Monitoring

Connect the MQTT Input node (Humidity) to the Dashboard Gauge node (Humidity).

MQTT Input (Humidity) --> Dashboard Gauge

This flow receives humidity readings and updates the humidity gauge in real time.

Complete Node-RED Flow

Once both flows are connected, your Node-RED workspace should look similar to this:

Smart Room Temperature Monitor Using ESP32, DHT22, MQTT and Node-RED

Deploy the Flow

After connecting the nodes:

  1. Click the Deploy button in the top-right corner of the Node-RED editor.
  2. Wait for the confirmation message indicating that the flow has been successfully deployed.
  3. Open the dashboard in your web browser.

Dashboard URL:

http://<RaspberryPi-IP>:1880/dashboard

Replace <RaspberryPi-IP> with the IP address of your Raspberry Pi or the computer running Node-RED.

For example:

http://192.168.29.142:1880/dashboard

Verify the Dashboard

If everything is configured correctly, the dashboard will automatically update every time the ESP32 publishes new sensor readings.

You should see:

  • 🌡️ Temperature Gauge showing the current room temperature.
  • 💧 Humidity Gauge displaying the current humidity level.

The values will refresh automatically without needing to reload the page, providing a live view of your room’s environmental conditions.

Sample Dashboard Output

Smart Room Temperature Monitor Using ESP32, DHT22, MQTT and Node-RED

Temperature: 28.8°C
Humidity: 69.1%

The values change in real time as environmental conditions change.

Real-World Applications

This simple project can be expanded into many useful IoT solutions.

Smart Home Monitoring

Monitor:

  • Living room temperature
  • Bedroom humidity
  • Indoor air conditions

Greenhouse Monitoring

Track:

  • Temperature
  • Humidity
  • Plant growing conditions

Server Room Monitoring

Monitor:

  • Equipment temperature
  • Cooling performance
  • Environmental conditions

Industrial IoT

Track:

  • Factory conditions
  • Storage room temperature
  • Warehouse monitoring

Possible Enhancements

Once the basic project is working, consider adding:

Email Alerts

Send notifications when temperature exceeds limits.

Mobile Dashboard

Access readings from smartphones.

Data Logging

Store readings in:

  • InfluxDB
  • MySQL
  • SQLite

Cloud Integration

Send data to:

  • AWS IoT
  • Firebase
  • ThingsBoard
  • Blynk

Relay Control

Automatically switch fans or air conditioners ON/OFF based on temperature.

Troubleshooting

No Sensor Readings

Check:

  • Wiring
  • GPIO pin number
  • Sensor power supply

MQTT Not Receiving Data

Verify:

  • Broker IP address
  • Wi-Fi connection
  • MQTT topic names

Dashboard Not Updating

Check:

  • MQTT Input node configuration
  • Node-RED deployment status
  • Mosquitto broker service

What to Learn Next

After completing this project, continue with:

  • MQTT Last Will and Testament (LWT)
  • MQTT Topics and Wildcards Explained
  • ESP32 Relay Control Using MQTT
  • Smart Home Automation Using ESP32 and Node-RED
  • MQTT Authentication and User Management

Conclusion

Building a Smart Room Temperature Monitor is an excellent way to combine ESP32, MQTT, Mosquitto, and Node-RED into a complete IoT project. It introduces real-world concepts such as sensor integration, MQTT messaging, dashboard creation, and remote monitoring.

More importantly, it demonstrates how multiple IoT technologies work together to create practical solutions. Once you’ve completed this project, you’ll have a strong foundation for building more advanced monitoring and automation systems.

Frequently Asked Questions

Why use DHT22 instead of DHT11?

DHT22 provides better accuracy, a wider temperature range, and improved humidity measurement.

Can I use ESP8266 instead of ESP32?

Yes. The project works with ESP8266 using minor code modifications.

Do I need Node-RED?

No. MQTT messages can be viewed using MQTT Explorer or custom applications, but Node-RED makes dashboard creation much easier.

Can I access the dashboard remotely?

Yes. By configuring port forwarding, VPN access, or cloud services, the dashboard can be accessed remotely.

Can I store historical sensor data?

Yes. Node-RED can be integrated with databases such as InfluxDB, MySQL, and PostgreSQL for long-term storage.

Related MQTT Tutorials:


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *