Build an ESP32 MQTT Smart Home System in 2026: Complete Guide with Code and Home Assistant Integration

Key Takeaway: Building a complete ESP32-based MQTT smart home system costs under Rs 1,200 per room. With an ESP32 microcontroller, DHT22 sensor, relay module, and the Mosquitto MQTT broker running on a Raspberry Pi, you can control lights, fans, and monitor temperature and humidity — all on your local network with zero cloud dependency. Home Assistant integration adds powerful automation rules like temperature-based fan control and sunset-triggered lighting.

ESP32 MQTT Smart Home System 2026
Complete Build Guide: Sensors, Relays, Home Assistant & Automation

Rs 1,200
Cost per Room Setup

5 min
MQTT Message Delivery

100%
Local Network, No Cloud

System Architecture
ESP32 nodes in each room (sensors + relays)
Mosquitto MQTT Broker on Raspberry Pi
Home Assistant for dashboards and automations
Node-RED for lightweight dashboard alternative
100% local network – zero cloud dependency

Hardware per Room
ESP32 Dev Board: Rs 350-500
DHT22 Temp/Humidity Sensor: Rs 150
2-Channel Relay Module: Rs 100
PIR Motion Sensor: Rs 80
Total: ~Rs 1,200 per room

MQTT Flow: Sensor -> ESP32 -> Broker -> Home Assistant
Publish: home/bedroom/temperature | Subscribe: home/light/set | Retained for state tracking

Automations: Fan ON > 30C | Porch Light at Sunset | All OFF on Departure
Customize with Home Assistant YAML or Node-RED flow editor

Sources: Zbotic, IoT Starters, KnowledgePitch, CircuitOfThings | Data as of July 2026

ESP32 MQTT smart home system architecture, hardware requirements, and automation examples

Why ESP32 for Smart Home Automation?

The ESP32 microcontroller is the perfect foundation for DIY smart home projects. It offers built-in Wi-Fi and Bluetooth, dual-core processing, ample GPIO pins, and a massive ecosystem of libraries — all at a price point of Rs 350-500. Combined with the MQTT protocol, it creates a reliable, local-first smart home system that works even when the internet goes down.

This guide walks you through building a complete smart home node: temperature and humidity monitoring, relay-controlled lights and fans, motion-triggered automation, and integration with Home Assistant for a polished dashboard. Total component cost per room: under Rs 1,200.

System Architecture Overview

A well-designed ESP32 smart home follows a three-layer architecture:

1. Edge Layer: ESP32 nodes placed in each room. Each node reads sensors (DHT22 for temperature/humidity, PIR for motion) and controls relays (lights, fans, appliances).

2. Communication Layer: MQTT broker (Mosquitto) running on a Raspberry Pi 4 or Pi Zero 2W. The broker routes messages between ESP32 nodes and the dashboard using a publish/subscribe model.

3. Application Layer: Home Assistant provides the dashboard and automation engine. Node-RED is a lightweight alternative for simpler setups.

All communication stays on your local network. No cloud services, no subscription fees, no data leaving your home.

Hardware Requirements (Per Room)

Component Approx Cost Purpose
ESP32 Dev Board Rs 350-500 Microcontroller with Wi-Fi/BT
DHT22 Sensor Rs 150 Temperature (-40 to 80C) and humidity
2-Ch Relay Module Rs 100 Control lights/fans (5V)
HC-SR501 PIR Sensor Rs 80 Motion detection
Jumper Wires + Breadboard Rs 100 Prototyping
Total Per Room ~Rs 1,200

For the central hub, a Raspberry Pi 4 (Rs 4,000-6,000) runs Mosquitto MQTT broker and Home Assistant. Alternatively, use a free cloud MQTT broker like HiveMQ Cloud for testing with zero hardware investment.

Setting Up the Mosquitto MQTT Broker

Mosquitto is the most popular MQTT broker for home automation. Install it on your Raspberry Pi:

sudo apt update
sudo apt install mosquitto mosquitto-clients
sudo systemctl enable mosquitto

For security, set up authentication:

sudo mosquitto_passwd -c /etc/mosquitto/passwd homeuser
# Enter password when prompted

sudo nano /etc/mosquitto/mosquitto.conf
# Add:
# password_file /etc/mosquitto/passwd
# allow_anonymous false

sudo systemctl restart mosquitto

Test the broker from another machine:

mosquitto_sub -h 192.168.1.100 -t "test" -u homeuser -P yourpassword
mosquitto_pub -h 192.168.1.100 -t "test" -m "Hello MQTT" -u homeuser -P yourpassword

ESP32 Code: Publishing Sensor Data and Receiving Commands

The following complete Arduino sketch reads a DHT22 sensor, publishes temperature and humidity every 30 seconds, and subscribes to relay control commands. Install the PubSubClient and DHT sensor library via the Arduino IDE Library Manager before uploading.

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

// --- WiFi Configuration ---
const char* ssid = "YourWiFiSSID";
const char* password = "YourWiFiPassword";

// --- MQTT Configuration ---
const char* mqtt_server = "192.168.1.100";
const int mqtt_port = 1883;
const char* mqtt_user = "homeuser";
const char* mqtt_password = "yourpassword";

// --- MQTT Topics ---
const char* topic_temp = "home/bedroom/temperature";
const char* topic_humid = "home/bedroom/humidity";
const char* topic_status = "home/bedroom/status";
const char* topic_cmd = "home/bedroom/relay/set";
const char* topic_relay_state = "home/bedroom/relay/state";

// --- Hardware Pins ---
#define DHT_PIN 4
#define RELAY_PIN 26

DHT dht(DHT_PIN, DHT22);
WiFiClient espClient;
PubSubClient mqtt(espClient);

unsigned long lastPublish = 0;
#define PUBLISH_INTERVAL 30000

void setup() {
  Serial.begin(115200);
  pinMode(RELAY_PIN, OUTPUT);
  digitalWrite(RELAY_PIN, LOW);
  dht.begin();
  
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
  
  mqtt.setServer(mqtt_server, mqtt_port);
  mqtt.setCallback(callback);
}

void connectMQTT() {
  while (!mqtt.connected()) {
    String clientId = "ESP32-Bedroom-" + String(random(0xffff), HEX);
    if (mqtt.connect(clientId.c_str(), mqtt_user, mqtt_password,
                     topic_status, 1, true, "offline")) {
      mqtt.publish(topic_status, "online", true);
      mqtt.subscribe(topic_cmd);
    } else {
      delay(5000);
    }
  }
}

void callback(char* topic, byte* payload, unsigned int length) {
  String message;
  for (int i = 0; i < length; i++) message += (char)payload[i];
  
  if (String(topic) == topic_cmd) {
    if (message == "ON") {
      digitalWrite(RELAY_PIN, HIGH);
      mqtt.publish(topic_relay_state, "ON", true);
    } else if (message == "OFF") {
      digitalWrite(RELAY_PIN, LOW);
      mqtt.publish(topic_relay_state, "OFF", true);
    }
  }
}

void publishSensorData() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  
  if (isnan(h) || isnan(t)) {
    Serial.println("Sensor read failed");
    return;
  }
  
  char tempStr[8], humStr[8];
  dtostrf(t, 1, 1, tempStr);
  dtostrf(h, 1, 0, humStr);
  
  mqtt.publish(topic_temp, tempStr, true);
  mqtt.publish(topic_humid, humStr, true);
}

void loop() {
  if (!mqtt.connected()) connectMQTT();
  mqtt.loop();
  
  if (millis() - lastPublish > PUBLISH_INTERVAL) {
    publishSensorData();
    lastPublish = millis();
  }
}

Home Assistant Integration

Home Assistant natively supports MQTT. Add your ESP32 devices to configuration.yaml:

mqtt:
  sensor:
    - name: "Bedroom Temperature"
      state_topic: "home/bedroom/temperature"
      unit_of_measurement: "°C"
      device_class: temperature
      
    - name: "Bedroom Humidity"
      state_topic: "home/bedroom/humidity"
      unit_of_measurement: "%"
      device_class: humidity
  
  switch:
    - name: "Bedroom Light"
      state_topic: "home/bedroom/relay/state"
      command_topic: "home/bedroom/relay/set"
      payload_on: "ON"
      payload_off: "OFF"
      state_on: "ON"
      state_off: "OFF"
      
  binary_sensor:
    - name: "Bedroom Controller"
      state_topic: "home/bedroom/status"
      payload_on: "online"
      payload_off: "offline"
      device_class: connectivity

After restarting Home Assistant, your ESP32 sensors and switches appear on the dashboard automatically.

Creating Power Automations

Home Assistant automations turn raw sensor data into intelligent actions:

Temperature-Based Fan Control

automation:
  - alias: "Turn on fan when hot"
    trigger:
      platform: numeric_state
      entity_id: sensor.bedroom_temperature
      above: 30
    action:
      service: switch.turn_on
      target:
        entity_id: switch.bedroom_fan

Sunset Lighting

  - alias: "Porch light at sunset"
    trigger:
      platform: sun
      event: sunset
      offset: "+00:15:00"
    action:
      service: switch.turn_on
      target:
        entity_id: switch.porch_light

Presence-Based All-Off

  - alias: "All off when leaving"
    trigger:
      platform: state
      entity_id: device_tracker.your_phone
      to: "not_home"
      for: "00:05:00"
    action:
      service: switch.turn_off
      target:
        entity_id:
          - switch.bedroom_light
          - switch.living_room_light
          - switch.kitchen_light

Node-RED Alternative Dashboard

If Home Assistant feels too heavy, Node-RED provides a lightweight web-based dashboard. Install Node-RED on your Raspberry Pi, add the node-red-dashboard palette, and create an MQTT-in node subscribing to home/bedroom/temperature. Wire it to a gauge widget for real-time display. Add an MQTT-out node publishing to home/bedroom/relay/set from a dashboard switch. Node-RED’s flow-based visual editor makes it accessible even for beginners.

3-Room System Cost Breakdown (India)

Item Quantity Cost
ESP32 Dev Boards 3 Rs 1,200
DHT22 Sensors 3 Rs 450
Relay Modules (4-Ch) 3 Rs 450
PIR Sensors 3 Rs 240
Raspberry Pi 4 (hub) 1 Rs 5,000
Wires + Enclosures Rs 500
Total ~Rs 7,840

If you already have a Raspberry Pi, the cost drops to under Rs 3,000 for a full 3-room system. Using a free cloud MQTT broker instead of a Pi brings the total down to around Rs 2,800.

Frequently Asked Questions

What happens if the MQTT broker goes down?

ESP32 nodes lose MQTT connectivity and cannot receive remote commands, but locally implemented physical buttons continue to work. The PubSubClient library auto-reconnects when the broker comes back. Retained messages and Last Will and Testament (LWT) ensure status is restored automatically.

Can I use MQTT without Home Assistant?

Absolutely. You can build a complete system with just Mosquitto and ESP32 devices. Each ESP32 can subscribe to commands from other devices directly. Home Assistant adds the dashboard and automation engine but is not required.

What MQTT QoS level should I use?

QoS 0 (fire and forget) for frequent sensor readings. QoS 1 (at least once) for switch commands that must not be missed. QoS 2 (exactly once) is rarely needed in home automation. Set the retained flag on sensor topics so new subscribers immediately get the last known value.

Can I control the system remotely when away from home?

Yes. Use a cloud MQTT broker like HiveMQ Cloud (free tier available) for simple setups, Nabu Casa for Home Assistant cloud access, or self-host with Tailscale VPN (free for personal use) for secure remote access without subscriptions.

How many ESP32 devices can one Mosquitto broker handle?

Mosquitto is extremely lightweight. On a Raspberry Pi 4, it comfortably handles 1,000+ concurrent connections at typical home message rates. For a standard home with 10-50 nodes, resource usage is negligible.

Can I add more sensors later?

Yes. MQTT’s publish/subscribe model makes expansion trivially easy. Add a new ESP32 node for the kitchen, publish to home/kitchen/temperature, and Home Assistant auto-discovers it if you follow the MQTT Discovery topic format. No hub reconfiguration needed.

Final Thoughts

Building an ESP32-based smart home system is one of the most rewarding IoT projects you can tackle in 2026. For an investment of around Rs 1,200 per room, you get professional-grade automation: temperature monitoring, relay control, motion-triggered lighting, cloud-free operation, and integration with Home Assistant or Node-RED.

The system is modular, expandable, and fully under your control. No subscription fees, no privacy concerns, no dependency on proprietary hubs. Start with one room, refine the code, and scale to your entire home as you gain confidence.

Sources

  1. Zbotic: MQTT Home Automation with ESP32, Mosquitto, and Home Assistant
  2. IoT Starters: MQTT Smart Home Automation with ESP32 and Node-RED
  3. KnowledgePitch: Build a Smart Home with ESP32 and MQTT
  4. CircuitOfThings: ESP32 MQTT Tutorial
  5. Zbotic: How to Build a Smart Home with ESP32 and Sensors

Disclosure: Some links in this article are affiliate links. We may earn a small commission at no extra cost to you. All research and code is independent.

You are currently viewing Build an ESP32 MQTT Smart Home System in 2026: Complete Guide with Code and Home Assistant Integration

Leave a Reply