NEW Free Trial Class — Book now, start learning this week. Reserve Your Spot →
Book FREE Trial Talk to a Mentor
IoT

Build a Smart Home System with ESP32 and MQTT: Step-by-Step Tutorial

Build a Smart Home System with ESP32 and MQTT: Step-by-Step Tutorial

The Internet of Things (IoT) is connecting everything around us to the internet — your AC, your water tank, your door lock. Building your own smart home system is one of the most satisfying IoT projects because you use it every day, and it solves a real problem in your own house.

In this tutorial, we'll build a system that lets you control a light and a fan from your smartphone, anywhere in the world, and also monitor temperature and humidity in real time. Total component cost: under ₹1,200.

What You'll Need

Understanding MQTT

MQTT is a lightweight messaging protocol designed for IoT devices. It works on a publish/subscribe model: devices can publish messages to "topics" (like channels), and other devices can subscribe to receive those messages.

Example: Your phone publishes "ON" to the topic home/bedroom/light. Your ESP32 is subscribed to that topic — it receives the message and turns the relay on. This works over the internet because both devices connect to a shared MQTT "broker" (server).

Step 1: Setup HiveMQ Cloud Broker

Go to hivemq.com and create a free account. Create a new cluster and note your:

Step 2: Wire the Hardware

Connect the DHT22 data pin to ESP32 GPIO 4. Connect relay IN1 to GPIO 26 and IN2 to GPIO 27. Power both from ESP32's 3.3V and GND pins. The relay's output terminals connect between your appliance's live wire and the power supply — be careful with mains voltage; if unsure, use a 5V LED instead of a real appliance for testing.

Step 3: Install Libraries in Arduino IDE

Open Arduino IDE, go to Library Manager and install: PubSubClient (for MQTT), DHT sensor library by Adafruit, and ArduinoJson.

Step 4: The ESP32 Code

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

// --- Config ---
const char* ssid = "YOUR_WIFI_NAME";
const char* password = "YOUR_WIFI_PASSWORD";
const char* mqtt_server = "YOUR_HIVEMQ_HOSTNAME";
const char* mqtt_user = "YOUR_USERNAME";
const char* mqtt_pass = "YOUR_PASSWORD";

#define RELAY1 26
#define RELAY2 27
#define DHTPIN 4
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);
WiFiClientSecure espClient;
PubSubClient client(espClient);

void callback(char* topic, byte* payload, unsigned int length) {
  String msg = "";
  for (int i = 0; i < length; i++) msg += (char)payload[i];
  
  if (String(topic) == "home/light") {
    digitalWrite(RELAY1, msg == "ON" ? LOW : HIGH);
  }
  if (String(topic) == "home/fan") {
    digitalWrite(RELAY2, msg == "ON" ? LOW : HIGH);
  }
}

void setup() {
  pinMode(RELAY1, OUTPUT); pinMode(RELAY2, OUTPUT);
  digitalWrite(RELAY1, HIGH); digitalWrite(RELAY2, HIGH);
  dht.begin();
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) delay(500);
  
  espClient.setInsecure(); // for testing; use cert in production
  client.setServer(mqtt_server, 8883);
  client.setCallback(callback);
  client.connect("ESP32", mqtt_user, mqtt_pass);
  client.subscribe("home/light");
  client.subscribe("home/fan");
}

void loop() {
  client.loop();
  // Publish sensor data every 10 seconds
  static unsigned long last = 0;
  if (millis() - last > 10000) {
    last = millis();
    float t = dht.readTemperature();
    float h = dht.readHumidity();
    char buf[50];
    sprintf(buf, "{"temp":%.1f,"humidity":%.1f}", t, h);
    client.publish("home/sensors", buf);
  }
}

Step 5: Control From Your Phone

Open MQTT Explorer on your phone, connect to your HiveMQ broker with the same credentials, and publish "ON" to home/light. Your relay should click and the connected device will turn on. Publish "OFF" to turn it off. You can now control it from anywhere with internet access.

What to Build Next

This project is part of our Engineer-level curriculum at KnowledgePitch. Students who complete the full IoT module graduate with 3–4 working smart home devices and a solid understanding of cloud connectivity, sensor networks, and remote control systems.

Turn Reading Into Building

Come to MakersPitch Lab and build what you just read about — in a real lab, with real components, guided by expert mentors.