DIY Smart Home Automation:
Build Your Own IoT Sensor Network from Scratch
A practical, step-by-step guide to designing, wiring, and deploying a WiFi-connected sensor network using ESP32, MQTT, and Home Assistant — no cloud subscription required.
Commercial smart home kits are convenient, but they come with recurring fees, privacy trade-offs, and a hard ceiling on customization. Building your own IoT sensor network costs a fraction of the price, gives you complete data ownership, and teaches you embedded systems, networking, and software integration all at once. In this guide you will go from a blank workbench to a live home automation dashboard — measuring temperature, humidity, and motion across every room — using open-source tools that run entirely on your local network.
1. Choosing Your Microcontroller
Two chips dominate the DIY IoT world: the ESP8266 and the ESP32. Both are WiFi-capable, run on 3.3 V logic, and are programmed via the Arduino IDE or MicroPython. The ESP32 is the better choice for new projects — it adds Bluetooth, dual-core processing, more GPIO pins, and hardware encryption at a price difference of roughly $1–2.
| Feature | ESP8266 (NodeMCU) | ESP32 (DevKit v1) |
|---|---|---|
| CPU cores | 1 × 80 MHz | 2 × 240 MHz |
| Flash | 4 MB | 4–16 MB |
| GPIO pins | 11 usable | 30+ usable |
| WiFi | 802.11 b/g/n | 802.11 b/g/n |
| Bluetooth | No | BLE 4.2 + Classic |
| ADC channels | 1 (10-bit) | 18 (12-bit) |
| Deep sleep current | ~20 ยตA | ~10 ยตA |
| Typical price | $2–4 | $4–6 |
2. Sensor Selection Guide
Temperature & Humidity — DHT22 vs. SHT31
The DHT22 (AM2302) is the beginner's workhorse: single-wire digital output, ±0.5 °C accuracy, ±2–5% RH, and $2–4 each. The SHT31 communicates over I2C, is more accurate (±0.3 °C, ±2% RH), and supports two addresses on the same bus — ideal when you need two sensors on one node. For most home automation use cases, the DHT22 is entirely sufficient.
Motion Detection — PIR (HC-SR501)
A passive infrared sensor detects heat movement from humans and pets. The HC-SR501 costs under $1, runs at 5 V (with a 3.3 V-tolerant output), and has two potentiometers to adjust sensitivity and hold time. Mount it at 2 m height, angled 15–20° downward, with at least 3 m clearance for reliable detection.
Additional Sensor Ideas
Once your base network is stable, expand easily: MQ-2 for smoke/gas detection, BH1750 for lux-accurate ambient light, HC-SR04 ultrasonic for presence detection without a PIR, or a DS18B20 waterproof probe for water heater or pipe monitoring.
3. Parts List & Estimated Cost
Below is a complete bill of materials for a three-node sensor network including the central hub. Prices are sourced from AliExpress/Amazon as of early 2026 and reflect single-unit pricing; buying in packs of 5–10 cuts costs by 30–40%.
| Component | Qty | Unit Price | Total |
|---|---|---|---|
| ESP32 DevKit v1 | 3 | $5.00 | $15.00 |
| DHT22 sensor (with breakout) | 3 | $2.50 | $7.50 |
| HC-SR501 PIR sensor | 3 | $0.90 | $2.70 |
| 10 kฮฉ resistors (pack of 100) | 1 | $1.20 | $1.20 |
| 100 nF ceramic capacitors (pack) | 1 | $1.00 | $1.00 |
| Prototyping PCB (5 cm × 7 cm, 3-pack) | 1 | $2.50 | $2.50 |
| USB-A to micro/USB-C cables | 3 | $1.50 | $4.50 |
| 5 V USB wall adapters | 3 | $2.00 | $6.00 |
| Raspberry Pi 4 (2 GB) — hub | 1 | $35.00 | $35.00 |
| 32 GB microSD card | 1 | $6.00 | $6.00 |
| Jumper wires assortment | 1 | $3.50 | $3.50 |
| 3D-printed or ABS enclosures | 3 | $2.00 | $6.00 |
| Estimated Total (3-node system) | $90.90 | ||
| Excluding Raspberry Pi (if you have one) | $55.90 | ||
4. Setting Up the MQTT Broker & Home Assistant Hub
Install Home Assistant OS on your Raspberry Pi — the official image handles Mosquitto, Node-RED, and InfluxDB as supervised add-ons with a few clicks. Flash the image with Balena Etcher, boot, navigate to http://homeassistant.local:8123, and complete the onboarding wizard. Then install the Mosquitto broker add-on:
In Home Assistant: Settings → Add-ons → Mosquitto broker → Install → Start. Enable "Start on boot" and "Watchdog". In the add-on configuration, create a dedicated MQTT user with a strong password — do not use your HA admin credentials.
Settings → Devices & Services → Add Integration → MQTT. Enter
192.168.1.50 (your Pi's static IP), port 1883, and the credentials you just created. Home Assistant will now auto-discover devices that publish their config to homeassistant/ topics.
In your router's DHCP settings, reserve
192.168.1.50 for the Pi's MAC address. This prevents your nodes from losing their broker if the Pi gets a new lease after a reboot.
5. Programming the ESP32 Sensor Node
The firmware below uses the Arduino framework with the PubSubClient MQTT library and the DHTesp library. Install both via the Arduino Library Manager. The node publishes temperature, humidity, and motion state every 30 seconds, plus an immediate publish whenever the PIR fires.
#include <WiFi.h>
#include <PubSubClient.h>
#include <DHTesp.h>
// ── Config ─────────────────────────────────────────
const char* SSID = "YourWiFiSSID";
const char* WIFI_PASS = "YourWiFiPassword";
const char* MQTT_HOST = "192.168.1.50";
const int MQTT_PORT = 1883;
const char* MQTT_USER = "sensor_user";
const char* MQTT_PASS = "strongPassword123";
const char* NODE_ID = "bedroom"; // unique per node
// ── Pins ────────────────────────────────────────────
#define DHT_PIN 4
#define PIR_PIN 5
DHTesp dht;
WiFiClient espClient;
PubSubClient mqtt(espClient);
unsigned long lastPublish = 0;
const unsigned long INTERVAL = 30000; // 30 s
// ── Helpers ─────────────────────────────────────────
void connectWifi() {
WiFi.begin(SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) delay(500);
}
void connectMqtt() {
String clientId = String("esp32-") + NODE_ID;
while (!mqtt.connected()) {
if (mqtt.connect(clientId.c_str(), MQTT_USER, MQTT_PASS)) break;
delay(3000);
}
}
void publishSensors() {
TempAndHumidity th = dht.getTempAndHumidity();
char topic[64], payload[64];
snprintf(topic, sizeof(topic), "home/%s/temperature", NODE_ID);
snprintf(payload, sizeof(payload), "%.1f", th.temperature);
mqtt.publish(topic, payload, true); // retained
snprintf(topic, sizeof(topic), "home/%s/humidity", NODE_ID);
snprintf(payload, sizeof(payload), "%.1f", th.humidity);
mqtt.publish(topic, payload, true);
}
// ── Setup / Loop ────────────────────────────────────
void setup() {
Serial.begin(115200);
pinMode(PIR_PIN, INPUT);
dht.setup(DHT_PIN, DHTesp::DHT22);
connectWifi();
mqtt.setServer(MQTT_HOST, MQTT_PORT);
connectMqtt();
}
void loop() {
if (!mqtt.connected()) connectMqtt();
mqtt.loop();
// Periodic sensor publish
if (millis() - lastPublish >= INTERVAL) {
publishSensors();
lastPublish = millis();
}
// Immediate PIR publish
static int lastPir = LOW;
int pir = digitalRead(PIR_PIN);
if (pir != lastPir) {
char topic[64];
snprintf(topic, sizeof(topic), "home/%s/motion", NODE_ID);
mqtt.publish(topic, pir ? "ON" : "OFF", true);
lastPir = pir;
}
}
secrets.h file excluded from version control, or provision credentials over BLE during device setup.
6. Building the Home Assistant Dashboard
Once your nodes are online and publishing, entities appear automatically in Home Assistant. Build a Lovelace dashboard with Gauge cards for temperature/humidity and a History Graph card for 24-hour trends. Here is what a three-room layout looks like:
7. PCB Design & Enclosure Tips
Once you have validated your breadboard prototype, move to a custom PCB. This is easier than it sounds: EasyEDA (free, browser-based) exports Gerber files directly to JLCPCB for fabrication. Here are the key design rules for sensor node PCBs:
PCB Layout Best Practices
Place decoupling capacitors (100 nF ceramic) as close as possible to the ESP32's 3.3 V pin — within 2 mm ideally. Route power traces at least 0.5 mm wide; signal traces for I2C/SPI can be 0.25 mm. Keep the WiFi antenna area (the curved PCB edge on ESP32 modules) completely free of copper pours and ground planes. A ground pour on the bottom layer significantly reduces noise on ADC readings.
Enclosure Options
Three practical paths: (1) 3D-printed ABS/PLA — design in Fusion 360 or grab a remix from Printables.com; add ventilation slots for accurate temperature readings. (2) Hammond die-cast aluminum — excellent EMC shielding for industrial areas but blocks WiFi; use an external antenna. (3) Re-purposed outlet boxes — cheapest option; drill a vent hole and glue a PIR dome to the face.
8. Automations, Alerts & Next Steps
With your sensor data flowing into Home Assistant, the real value unlocks through automations. Here are three practical examples to get you started:
Temperature-Based Thermostat Control
Create an automation that turns on a smart plug (running a space heater) when bedroom temperature drops below 19 °C and turns it off above 22 °C, but only between 10 PM and 7 AM. Home Assistant's automation editor makes this a five-minute task — no code required.
Motion-Activated Lighting
Trigger a Zigbee or Z-Wave light via the PIR sensor state. Add a "wait for state" condition so the light turns off 5 minutes after the last motion detection. Combine with a lux sensor to only trigger after sunset.
Anomaly Alerts
Use a template sensor to calculate a 30-minute rolling average of humidity. If it spikes above 75% (indicating a water leak or forgotten bathroom exhaust), push a notification to your phone via the Home Assistant companion app.
Where to Go from Here
Extend your IoT sensor network with: InfluxDB + Grafana for long-term historical dashboards; ESPHome (a YAML-based firmware framework) to eliminate Arduino boilerplate; Zigbee2MQTT for adding inexpensive Zigbee sensors without pairing to proprietary hubs; and custom PCB fabrication to package everything cleanly. The open-source ecosystem around Home Assistant and MQTT is vast — once you have the foundation laid, every new sensor takes minutes to integrate.
Conclusion
Building your own IoT smart home sensor network is one of the most rewarding DIY electronics projects you can undertake. For under $100 you get real-time environmental monitoring across your entire home, full local data sovereignty, unlimited customization, and a deep understanding of WiFi networking, embedded firmware, and home automation logic. The ESP32, Mosquitto MQTT, and Home Assistant stack is mature, well-documented, and actively maintained — a solid foundation that will serve you for years. Start with a single bedroom node, validate the pipeline end-to-end, then scale to as many rooms as you like. Happy building.
Comments
Post a Comment