Limited Time Your first expert consultation is free! Book now Book now

Back to MakerSpaceIoT Projects

IoT Smart Home with ESP32 (DHT11, MQ-2, PIR)

Heba 13

1. Project Overview

A small smart-home monitor built around an ESP32. A DHT11 module measures temperature and humidity, an MQ-2 module watches for smoke and gas, and a PIR sensor detects motion. A buzzer sounds when the gas reading goes above a limit. The ESP32 joins your Wi-Fi and serves a web dashboard that shows all readings on a phone or computer and has a button to switch an LED on and off. It is a suggested, reproducible design, not a tested product, and the MQ-2 is a hobby sensor, not a certified smoke or gas alarm.

Cover photo: a wooden smart-home model kit, provided by WadiMakers. It is a reference photo of a similar model and shows a different sensor set (LCD, RFID, servo, button). The build on this page uses the parts listed below.

Sources and credits: the idea and the sensor mix follow two open projects on Hackster.io, both marked with the MIT licence on their pages: "IoT Based Home Monitoring and Device Control Using Esp32" by VJ-Embedded-Tech (hackster.io/VJ-Embedded-Tech/iot-based-home-monitoring-and-device-control-using-esp32-95c601) and "DIY Gas Sensor Project with ESP32: Smoke Detection" by yaranaiotguru (hackster.io/yaranaiotguru/diy-gas-sensor-project-with-esp32-smoke-detection-5eee58). The wiring, diagram, tables, code and dashboard on this page were written for this page and are not copied from them. No photos were taken from Hackster.

2. How It Works

The ESP32 reads the sensors in a loop. The DHT11 is read every 2.5 seconds. The MQ-2 analog output is read through a 10k + 10k voltage divider, because the module runs on 5V and the ESP32 pin must never see more than 3.3V. The PIR output is a digital 3.3V signal. When the gas reading is above GAS_LIMIT (after a 1 minute warm-up) the buzzer turns on. The ESP32 also runs a small web server: the page at its IP address asks for /data every 2 seconds and shows the values, and the LED button calls /led.

3. Components Required

You also need your own computer with Arduino IDE 2 and a 2.4 GHz Wi-Fi network (the ESP32 does not use 5 GHz).

Click here to open the components table

4. Circuit Diagram

Wire the circuit as in the diagram. DHT11: VCC to 3V3, DATA to GPIO4, GND to GND. MQ-2: VCC to VIN (5V), GND to GND, and AO through the divider (10k in series, 10k to GND) to GPIO34. PIR: VCC to VIN, OUT to GPIO27, GND to GND. Buzzer: VCC to VIN, S to GPIO26, GND to GND. LED: GPIO25 through 220 ohm to the long leg, short leg to GND.

Click here to open the wiring diagram

Diagram colors: red = 5V, orange = 3V3, black = GND, other colors = signals. This is a teaching diagram with simplified pin positions, not a photo of a tested build.

5. Wiring Table

Read each row from the From pin to the To pin and check power, ground and signals before you connect the USB cable. All GND pins join the ESP32 GND.

Click here to open the wiring table

6. Connection Steps

Wire the project in this order with the USB cable unplugged. The table has the same steps with a check for each.

  1. Install the ESP32 board package and the "DHT sensor library" (Adafruit, with Adafruit Unified Sensor) in Arduino IDE.
  2. Wire the circuit as in the wiring table, with a common GND.
  3. Check the MQ-2 divider: AO must never go straight to the ESP32.
  4. Type your Wi-Fi name and password in the code, choose ESP32 Dev Module and the right port, then upload.
  5. Open the Serial Monitor at 115200 baud and read the IP address.
  6. Open http://IP-ADDRESS in a browser on the same Wi-Fi.
  7. Wait 1 minute for the MQ-2 and PIR to warm up, then test.

Click here to open the connection steps table

7. Source Code

Upload this code to the ESP32 (file name smart_home_esp32.ino). Pins: DHT11 on GPIO4, MQ-2 on GPIO34, PIR on GPIO27, buzzer on GPIO26, LED on GPIO25. Change the Wi-Fi name and password first. GAS_LIMIT is a default: read the gas value on the dashboard in clean air and set the limit above it.

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

// Type your own Wi-Fi name and password (2.4 GHz network)
const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";

const int DHT_PIN = 4;
const int MQ2_PIN = 34;
const int PIR_PIN = 27;
const int BUZZER_PIN = 26;
const int LED_PIN = 25;

const int GAS_LIMIT = 1800;            // raw ADC 0-4095 after the divider, calibrate in clean air
const unsigned long WARMUP_MS = 60000; // MQ-2 and PIR need about 1 minute to warm up
const unsigned long DHT_EVERY_MS = 2500;

DHT dht(DHT_PIN, DHT11);
WebServer server(80);

float temperature = NAN;
float humidity = NAN;
int gasRaw = 0;
bool motion = false;
bool gasAlarm = false;
bool ledOn = false;
unsigned long lastDht = 0;

const char PAGE[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ESP32 Smart Home</title>
<style>
body { font-family: Arial, sans-serif; text-align: center; background: #f2f5fa; }
.card { display: inline-block; width: 150px; margin: 8px; padding: 14px; background: #fff; border-radius: 10px; }
.big { font-size: 26px; font-weight: bold; }
.alarm { color: #c00; }
button { font-size: 18px; padding: 10px 24px; margin-top: 10px; }
</style>
</head>
<body>
<h2>ESP32 Smart Home</h2>
<div class="card">Temperature<div class="big" id="t">--</div></div>
<div class="card">Humidity<div class="big" id="h">--</div></div>
<div class="card">Gas (raw)<div class="big" id="g">--</div></div>
<div class="card">Motion<div class="big" id="m">--</div></div>
<div class="card">Gas alarm<div class="big" id="a">--</div></div>
<br>
<button id="led">Toggle LED</button>
<script>
let ledState = false;
async function refresh() {
  try {
    const r = await fetch('/data');
    const d = await r.json();
    document.getElementById('t').textContent = d.t === null ? '--' : d.t + ' C';
    document.getElementById('h').textContent = d.h === null ? '--' : d.h + ' %';
    document.getElementById('g').textContent = d.gas;
    document.getElementById('m').textContent = d.motion ? 'Detected' : 'None';
    const a = document.getElementById('a');
    a.textContent = d.alarm ? 'ALARM' : 'OK';
    a.className = d.alarm ? 'big alarm' : 'big';
    ledState = d.led;
  } catch (e) {}
}
document.getElementById('led').onclick = async () => {
  await fetch('/led?on=' + (ledState ? 0 : 1));
  refresh();
};
setInterval(refresh, 2000);
refresh();
</script>
</body>
</html>
)rawliteral";

void handleRoot() {
  server.send_P(200, "text/html", PAGE);
}

void handleData() {
  String json = "{";
  json += "\"t\":";
  json += isnan(temperature) ? String("null") : String(temperature, 1);
  json += ",\"h\":";
  json += isnan(humidity) ? String("null") : String(humidity, 0);
  json += ",\"gas\":" + String(gasRaw);
  json += ",\"motion\":" + String(motion ? "true" : "false");
  json += ",\"alarm\":" + String(gasAlarm ? "true" : "false");
  json += ",\"led\":" + String(ledOn ? "true" : "false");
  json += "}";
  server.send(200, "application/json", json);
}

void handleLed() {
  ledOn = server.arg("on") == "1";
  digitalWrite(LED_PIN, ledOn ? HIGH : LOW);
  server.send(200, "text/plain", "ok");
}

void setup() {
  Serial.begin(115200);
  pinMode(PIR_PIN, INPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(BUZZER_PIN, LOW);
  digitalWrite(LED_PIN, LOW);
  dht.begin();

  WiFi.begin(WIFI_SSID, WIFI_PASS);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println();
  Serial.print("Open this address in your browser: http://");
  Serial.println(WiFi.localIP());

  server.on("/", handleRoot);
  server.on("/data", handleData);
  server.on("/led", handleLed);
  server.begin();
}

void loop() {
  server.handleClient();
  unsigned long now = millis();

  motion = digitalRead(PIR_PIN) == HIGH;
  gasRaw = analogRead(MQ2_PIN);
  gasAlarm = (now > WARMUP_MS) && (gasRaw > GAS_LIMIT);

  if (now - lastDht >= DHT_EVERY_MS) {
    lastDht = now;
    float h = dht.readHumidity();
    float t = dht.readTemperature();
    if (!isnan(h)) humidity = h;
    if (!isnan(t)) temperature = t;
  }

  digitalWrite(BUZZER_PIN, gasAlarm ? HIGH : LOW);
}

Still to verify on real hardware: the pins above with your exact modules, the DHT11 library version, the GAS_LIMIT value, buzzer polarity, and the PIR sensitivity and delay knobs.

8. Testing & Troubleshooting

  • Dashboard does not load: check the IP in the Serial Monitor, use the same Wi-Fi, and use a 2.4 GHz network.
  • Temperature shows --: check the DHT11 wiring and the library; the first reading takes a few seconds.
  • Gas alarm at power on: the MQ-2 needs about 1 minute to warm up and its readings drift; raise GAS_LIMIT after calibrating in clean air.
  • Gas value is always 0 or 4095: check the 10k + 10k divider and that AO goes to GPIO34 (an ADC1 pin).
  • PIR always high: wait 1 minute after power on and turn the sensitivity knob down.
  • Buzzer is silent or always on: check the S pin on GPIO26 and the module type (active, not passive).
  • ESP32 restarts: use a good USB cable and power source; the MQ-2 heater draws extra current.

9. Improvements

  • Add a relay module to switch a lamp or fan (only with a safe low-voltage load, or have a qualified person handle mains).
  • Log readings to a Google Sheet or a MQTT broker.
  • Add an LCD 1602 to show the readings on the device.
  • Send a notification when the gas alarm or the PIR triggers.

10. Safety

The code, wiring, pin choices and thresholds are not verified until the project is built and tested. This is a low-voltage USB-powered project and must not be connected to mains voltage. The MQ-2 is a hobby sensor and must not be used as the only protection against gas or smoke. Test gas only with a tiny puff of unlit lighter gas in a ventilated place, away from flames. Fritzing-style parts are not used; the diagram was drawn for this page.

Share
H
About the authorHeba
Share a useful question or note and the project team can reply in the discussion.

Comments & discussion (0)