DIY Smart Home Automation: Build Your Own IoT Sensor Network from Scratch
DIY Electronics · IoT · Home Automation

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.

April 28, 2026  ·  10 min read  ·  Intermediate Level

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.

What you will build A multi-node wireless sensor network: each node is an ESP32 board with sensors, powered over USB or a small LiPo battery, reporting data every 30 seconds via MQTT to a Raspberry Pi running Home Assistant. Total cost: roughly $35–$60 for a three-room deployment.
IoT Sensor Network Architecture Diagram showing three sensor nodes communicating via WiFi to a Raspberry Pi MQTT broker, which feeds Home Assistant and a mobile dashboard. IoT Sensor Network — System Architecture Sensor Node A ESP32 + DHT22 Bedroom ONLINE Sensor Node B ESP8266 + PIR Living Room ONLINE Home Assistant Raspberry Pi 4 192.168.1.50 ACTIVE MQTT Broker Mosquitto Port 1883 LISTENING WiFi 802.11 b/g/n Sensor Node C ESP32 + DHT22 + PIR — Kitchen
Figure 1 — Three sensor nodes communicate over WiFi to a Mosquitto MQTT broker on a Raspberry Pi, which feeds Home Assistant for automation logic and dashboards.

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.

FeatureESP8266 (NodeMCU)ESP32 (DevKit v1)
CPU cores1 × 80 MHz2 × 240 MHz
Flash4 MB4–16 MB
GPIO pins11 usable30+ usable
WiFi802.11 b/g/n802.11 b/g/n
BluetoothNoBLE 4.2 + Classic
ADC channels1 (10-bit)18 (12-bit)
Deep sleep current~20 ยตA~10 ยตA
Typical price$2–4$4–6
Tip — Use ESP32 for sensor nodes that need long battery life. Deep sleep + wake-on-interrupt lets a 1 000 mAh LiPo run a sensor node for weeks. ESP8266 is perfectly fine for mains-powered nodes where cost matters more.

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.

ESP32 Sensor Node Wiring Schematic Wiring diagram showing an ESP32 DevKit connected to a DHT22 temperature/humidity sensor and an HC-SR501 PIR motion sensor, with pin labels and power connections. ESP32 Sensor Node — Wiring Schematic ESP32 DevKit v1 3V3 GND GPIO4 GPIO5 GPIO13 GPIO14 GPIO15 VIN (5V) EN GND GPIO23 GPIO22 GPIO21 GPIO19 GPIO18 GPIO5 USB-C DHT22 Temp/Humidity VCC → 3V3 DATA→ GPIO4 GND → GND HC-SR501 PIR Motion VCC → VIN 5V OUT → GPIO5 GND → GND dome 10kฮฉ pull-up Power (3V3 / 5V) GND Signal / Data
Figure 2 — Wiring schematic for a dual-sensor node. DHT22 connects to 3.3 V with a 10 kฮฉ pull-up on the data line; PIR uses the 5 V rail for reliable detection.

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%.

ComponentQtyUnit PriceTotal
ESP32 DevKit v13$5.00$15.00
DHT22 sensor (with breakout)3$2.50$7.50
HC-SR501 PIR sensor3$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 cables3$1.50$4.50
5 V USB wall adapters3$2.00$6.00
Raspberry Pi 4 (2 GB) — hub1$35.00$35.00
32 GB microSD card1$6.00$6.00
Jumper wires assortment1$3.50$3.50
3D-printed or ABS enclosures3$2.00$6.00
Estimated Total (3-node system)$90.90
Excluding Raspberry Pi (if you have one)$55.90
Cost-saving tip JLCPCB and PCBWay offer 5 custom PCBs for $2 + shipping. If you plan more than 5 nodes, designing a proper PCB dramatically reduces assembly time and improves reliability over hand-soldered protoboards.

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:

1
Install Mosquitto
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.
2
Configure MQTT Integration
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.
3
Assign a Static IP
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;
  }
}
Security note Never hardcode credentials in production firmware you share publicly. Use a separate 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:

Home Assistant Sensor Dashboard Mockup A mockup of a Home Assistant Lovelace dashboard showing temperature, humidity, and motion cards for bedroom, living room, and kitchen sensor nodes. My Home HA Sensors Automations Energy BEDROOM Temperature 22.4° Target: 21 °C Humidity 54% Ideal: 40–60% Motion CLEAR Last: 14 min ago LIVING ROOM Temp 21.1° Motion DETECTED 24H TEMPERATURE HISTORY 25° 22° 19° 16° 00:00 06:00 12:00 18:00 Now Bedroom Living Room
Figure 3 — Home Assistant Lovelace dashboard mockup showing temperature gauges, humidity levels, motion status indicators, and a 24-hour temperature trend chart.

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.

Mounting tip for temperature accuracy Never mount a DHT22 node directly on the wall behind drywall — thermal mass from the structure skews readings by 1–3 °C. Use a standoff bracket to create at least 3 cm of air gap, and shield the sensor from direct sunlight or HVAC vents.
PCB Layout and Enclosure Design Side-by-side view of a custom PCB layout for the ESP32 sensor node and a 3D-printed enclosure with ventilation slots and a PIR dome aperture. PCB Layout & Enclosure Design Custom PCB — Top Layer ESP32-WROOM-32 38-pin module KEEP-OUT C1 C2 DHT22 PIR HDR USB-C ▓ GND pour (bottom layer) 3D-Printed Enclosure vents PIR dome USB M3 standoff bosses at corners 80 mm × 50 mm × 25 mm
Figure 4 — Custom PCB layout (left) showing ESP32 module, sensor footprints, and antenna keep-out zone; 3D-printed enclosure (right) with ventilation slots, PIR dome aperture, and M3 standoff bosses.

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.

Community resources The r/homeassistant subreddit, the Home Assistant Community Forums, and the ESPHome documentation site are excellent resources for troubleshooting and inspiration. MQTT Explorer (free desktop app) is invaluable for debugging message flow in real time.

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.

IoT ESP32 Smart Home MQTT Home Assistant DIY Electronics Sensor Network Home Automation ESPHome Raspberry Pi

Comments

Popular posts from this blog

10 Low Investment Business Ideas for Beginners in 2026 (Start Under $500)

10 Business Ideas You Can Start With $500 to $2,500 in 2026 (Beginner-Friendly & Profitable)