MQTT-Based Smart Home Automation Using ESP32 and Node-RED

MQTT-Based Smart Home Automation Using ESP32 and Node-RED

Contents hide
1. MQTT-Based Smart Home Automation Using ESP32 and Node-RED

MQTT-Based Smart Home Automation Using ESP32 and Node-RED

Introduction

Smart home automation is one of the most exciting applications of the Internet of Things (IoT). From controlling lights and fans to monitoring sensors and appliances, connected devices are transforming the way we interact with our homes.

In this MQTT Smart Home Automation project, you’ll learn how to build a complete system using an ESP32, Mosquitto MQTT Broker, and Node-RED Dashboard. This combination is widely used in IoT home automation projects because it provides reliable communication, real-time control, and easy scalability.

In previous tutorials, we learned how MQTT works, installed a Mosquitto MQTT broker, connected an ESP32 as an MQTT client, and built a Node-RED dashboard. Now we’ll bring everything together into a practical ESP32 smart home project.

By the end of this guide, you’ll have a working MQTT home automation system capable of controlling real devices through a web-based dashboard.

What You Will Build

In this project:

  • ESP32 connects to Wi-Fi
  • ESP32 connects to Mosquitto MQTT Broker
  • Node-RED dashboard sends control commands
  • MQTT transfers commands to ESP32
  • ESP32 controls a relay module
  • Relay switches a connected device ON or OFF
  • Device status is displayed on the dashboard

This ESP32 MQTT project demonstrates the same architecture used in many commercial smart home automation systems.

System Architecture

MQTT-Based Smart Home Automation Using ESP32 and Node-RED

Prerequisites

Before starting, ensure you have completed:

Hardware Requirements

You will need:

  • ESP32 Development Board
  • Single Channel Relay Module
  • Raspberry Pi running Mosquitto
  • Node-RED installed
  • Jumper Wires
  • Breadboard (optional)

Safety Note

For learning purposes, use the relay LED indicator or a low-voltage load first.

Avoid working directly with mains voltage unless you are experienced and follow proper electrical safety practices.

Understanding the Communication Flow

One of the biggest advantages of MQTT home automation is that devices do not need to communicate directly with each other.

When a user interacts with the Node-RED home automation dashboard, commands are sent through the MQTT broker and delivered to the appropriate ESP32 device.

The communication process looks like this:

  1. User clicks ON button in Node-RED.
  2. Node-RED publishes a message.
  3. Mosquitto MQTT Broker receives the message.
  4. ESP32 subscribes to the topic.
  5. ESP32 receives the command.
  6. ESP32 activates the relay.
  7. Connected device turns ON.
  8. ESP32 publishes status updates.
  9. Node-RED dashboard displays the current state.

This publish-subscribe architecture makes MQTT one of the most efficient protocols for smart home and IoT automation projects.

Relay Wiring

Connect the relay module to the ESP32.

Relay Pin ESP32 Pin
VCC 5V
GND GND
IN GPIO 23

You may use a different GPIO pin if desired.

MQTT Topics Used

Device Control Topic

home/livingroom/light/control

Device Status Topic

home/livingroom/light/status

Separating control and status topics makes the system easier to maintain as it grows.

ESP32 Smart Home Control Code

Install Required Libraries

Before uploading the code to your ESP32, you need to install the required libraries in the Arduino IDE.

Library 1: WiFi Library

The WiFi library allows the ESP32 to connect to your wireless network and communicate with the MQTT broker.

Good news: the WiFi library is included automatically when you install ESP32 board support in the Arduino IDE.

You do not need to install it separately.

To verify the ESP32 board package is installed:

  1. Open Arduino IDE.
  2. Navigate to Tools → Board → Boards Manager.
  3. Search for ESP32.
  4. Install ESP32 by Espressif Systems if it is not already installed.

Once installed, the WiFi library becomes available automatically.

Library 2: PubSubClient Library

PubSubClient is one of the most popular MQTT libraries for Arduino and ESP32 projects. It enables the ESP32 to publish messages to MQTT topics and subscribe to messages from an MQTT broker.

Install PubSubClient

  1. Open Arduino IDE.
  2. Navigate to Sketch → Include Library → Manage Libraries.
  3. In the Library Manager search box, type:
PubSubClient
  1. Locate:
PubSubClient by Nick O'Leary
  1. Click Install.

Verify Installation

Create a new Arduino sketch and add:

#include <WiFi.h>
#include <PubSubClient.h>
Void setup() {
Serial.begin(115200);
}
void loop() {
}

Click Verify.

If the sketch compiles successfully without errors, both libraries are installed correctly and your development environment is ready for MQTT communication.

Why These Libraries Are Required

Library Purpose
WiFi.h Connects ESP32 to a Wi-Fi network
PubSubClient.h Enables MQTT publish and subscribe communication

Together, these libraries allow the ESP32 to communicate with the Mosquitto MQTT broker and exchange data with Node-RED dashboards, sensors, and other IoT devices.

If you run into any trouble while uploading your code, you can find a step-by-step guide in the article below.

ESP32 programming using Arduino IDE

Upload the code below using Arduino.

#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = “YOUR_WIFI”;
const char* password = “YOUR_PASSWORD”;
const char* mqtt_server = “192.168.1.150”;
WiFiClient espClient;
PubSubClient client(espClient);
#define RELAY_PIN 23
void callback(char* topic, byte* payload, unsigned int length) {
String message;
for (int i = 0; i < length; i++) {
message += (char)payload[i];
}
if (message == “ON”) {
digitalWrite(RELAY_PIN, HIGH);
client.publish(“home/livingroom/light/status”, “ON”);
}
if (message == “OFF”) {
digitalWrite(RELAY_PIN, LOW);
client.publish(“home/livingroom/light/status”, “OFF”);
}
}
void reconnect() {
while (!client.connected()) {
if (client.connect(“ESP32SmartHome”)) {
client.subscribe(“home/livingroom/light/control”);
} else {
delay(5000);
}
}
}
void setup() {
pinMode(RELAY_PIN, OUTPUT);
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
Copy paste the above code in Arduino IDE and save it. Also go to Edit and click on Auto Format.

Creating the Node-RED Dashboard

Now that the ESP32 is publishing and subscribing to MQTT topics, let’s build a simple web dashboard using Node-RED.

The dashboard will allow you to:

  • Turn the relay ON and OFF from a web browser
  • View the current relay status in real time
  • Control connected devices without modifying the ESP32 code

Dashboard Overview

The dashboard consists of two main functions:

  1. Send control commands to the ESP32
  2. Display the current device status

Communication between Node-RED and the ESP32 takes place through the Mosquitto MQTT broker.

Step 1: Create a Dashboard Switch

Open the Node-RED editor in your browser.

Example:

http://<RaspberryPi-IP>:1880

From the left panel, drag the following nodes onto the workspace:

  • Dashboard Switch (ui_switch)
  • MQTT Output (mqtt out)

Configure the Dashboard Switch node:

Label:

Living Room Light

ON Payload:

ON

OFF Payload:

OFF

These payloads will be sent whenever the user toggles the switch.

Step 2: Configure MQTT Output Node

Double-click the MQTT Output node.

Click on the + icon and configure below

MQTT-Based Smart Home Automation Using ESP32 and Node-RED

Configure:

Server:

192.168.1.150

(Replace with your Raspberry Pi MQTT broker IP.)

Port:

1883

Topic:

home/livingroom/light/control

This topic will be used to send commands to the ESP32.

Step 3: Connect the Nodes

Create the following flow:

Dashboard Switch
        ↓
     MQTT Out

What happens?

  • User clicks ON
  • Node-RED publishes “ON”
  • Mosquitto receives the message
  • ESP32 receives the command
  • Relay turns ON

The same process occurs when OFF is selected.

Step 4: Deploy the Flow

MQTT-Based Smart Home Automation Using ESP32 and Node-RED

Click the Deploy button in the top-right corner.

Your dashboard can now send MQTT commands to the ESP32.

Display Device Status

Controlling the relay is useful, but it is also important to know whether the device is currently ON or OFF.

To achieve this, the ESP32 publishes its current state to another MQTT topic.

Example topic:

home/livingroom/light/status

Step 5: Add Status Monitoring Nodes

Drag the following nodes onto the workspace:

  • MQTT Input (mqtt in)
  • Text

Configure MQTT Input

Set:

Server:

192.168.1.150

Port:

1883

Topic:

home/livingroom/light/status

This node listens for status updates published by the ESP32.

Configure Dashboard Text Node

Set:

Label:

Relay Status

Value Format:

{{msg.payload}}

This will display the latest MQTT message received from the ESP32.

Step 6: Connect the Nodes

Create the following flow:

MQTT In
    ↓
Text Widget

Click Deploy again.

Testing the Dashboard

Open your Node-RED Dashboard.

Example:

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

You should now see:

  • A switch to control the relay
  • A status field showing ON or OFF

MQTT-Based Smart Home Automation Using ESP32 and Node-RED

Test Procedure

  1. Turn the switch ON.
  2. ESP32 receives the MQTT command.
  3. Relay activates.
  4. ESP32 publishes status “ON”.
  5. Dashboard displays ON.

Repeat the process with OFF.

If everything is configured correctly, the dashboard status should always match the actual relay state.

Final Dashboard Architecture

MQTT-Based Smart Home Automation Using ESP32 and Node-RED

This architecture forms the foundation of many real-world smart home automation systems, where users control devices through a dashboard while receiving real-time status updates from connected IoT devices.

Expanding the System

Once one device works, scaling becomes easy.

Multiple Lights

Topics:

home/livingroom/light1/control

home/livingroom/light2/control

home/bedroom/light/control

Fan Control

Topic:

home/livingroom/fan/control

Smart Plug

Topic:

home/office/socket/control

Using topic hierarchies helps organize large smart home deployments.

Real-World Applications

Smart Lighting

Control lights remotely from a dashboard.

Fan Automation

Automatically control fans based on room temperature.

Home Security

Control alarms and monitoring systems.

Energy Management

Monitor and control power consumption.

Smart Irrigation

Activate water pumps using MQTT commands.

Common Issues and Troubleshooting

ESP32 Not Receiving Commands

Verify:

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

Relay Not Switching

Check:

  • Wiring connections
  • Relay supply voltage
  • GPIO pin assignment

Dashboard Not Updating

Verify:

  • Status topic matches exactly
  • MQTT nodes are connected
  • Node-RED is running

Remember that MQTT topics are case-sensitive.

Why MQTT is Perfect for Smart Homes

MQTT offers several advantages:

  • Lightweight communication
  • Low bandwidth usage
  • Real-time updates
  • Reliable message delivery
  • Easy integration with Node-RED
  • Supports hundreds of connected devices

These features make MQTT one of the most widely used protocols in home automation systems.

Conclusion

In this tutorial, you built a complete MQTT-based smart home automation system using ESP32, Mosquitto, and Node-RED. The dashboard can control devices through MQTT topics, while the ESP32 listens for commands and operates a relay module.

This project demonstrates how modern IoT systems are built using a publish-subscribe architecture. Once you understand this pattern, you can expand the system to control multiple devices, monitor sensors, and create fully automated smart home solutions.

The same architecture is used in commercial smart home platforms, industrial automation systems, and large-scale IoT deployments.

Frequently Asked Questions

Why use MQTT for home automation?

MQTT is lightweight, fast, and designed specifically for machine-to-machine communication, making it ideal for IoT devices.

Can multiple ESP32 devices connect to the same MQTT broker?

Yes. A single MQTT broker can manage many publishers and subscribers simultaneously.

Can I control devices from my phone?

Yes. The Node-RED dashboard is accessible from mobile browsers.

Does MQTT require internet access?

No. MQTT can operate entirely on a local network using a local broker such as Mosquitto.

Can I add sensors to this project?

Absolutely. Temperature, humidity, motion, air quality, and soil moisture sensors can all publish data through MQTT.

Is MQTT secure for smart homes?

Yes, especially when combined with TLS encryption and authentication as covered in the MQTT Security with TLS tutorial.

Next Steps

Continue building your smart home system:

  • ESP32 GPIO Basics
  • ESP32 DHT22 Temperature Monitoring
  • Smart Irrigation System Using ESP32 and MQTT
  • Multi-Room Home Automation Dashboard
  • ESP32 Deep Sleep for Battery-Powered Devices
  • ESP32 Learning Path
  • MQTT Learning Path

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 *