Advertisement
Intermediate Time: 4–6 weeks Electrical Engineering

Smart Home Automation System

Design and build a complete smart home system that controls lights, fans, appliances, and security using IoT.

IoTArduinoRaspberry PiWiFiRelaySensors
DifficultyIntermediate
Duration4–6 weeks
Components12 items
Steps12 steps

Introduction

A Smart Home Automation System integrates various home appliances and systems into a unified, centrally controlled network using the Internet of Things (IoT) technology. This project enables homeowners to remotely monitor and control devices such as lights, fans, air conditioning units, security cameras, door locks, and power outlets through a smartphone application or voice commands. The system leverages microcontrollers like Arduino or Raspberry Pi as the brain, communicating over WiFi or Bluetooth protocols. Modern smart home systems significantly reduce energy consumption by intelligently scheduling operations and detecting occupancy patterns. They also enhance security through real-time alerts, motion detection, and remote access to surveillance feeds. This project introduces students to embedded systems programming, wireless communication protocols (MQTT, HTTP, WebSocket), relay interfacing, sensor data acquisition, and cloud integration using platforms like AWS IoT or Firebase. The automation logic can be as simple as a timer-based schedule or as sophisticated as machine learning-driven predictions that learn from user behavior.

Theory & Background

Smart home automation works on the principle of interconnected devices communicating through a central hub or cloud server. The architecture follows a three-tier model: (1) Perception layer — sensors collect data (temperature, motion, light levels), (2) Network layer — data is transmitted using WiFi (IEEE 802.11), Zigbee (IEEE 802.15.4), or Z-Wave protocols, and (3) Application layer — cloud platforms process data and present it through apps. Communication between the microcontroller and cloud is handled via the MQTT protocol, a lightweight publish-subscribe messaging protocol ideal for constrained IoT devices. Relay modules act as electrically controlled switches that allow low-power microcontrollers to switch high-voltage AC loads safely. Optoisolators in relay boards electrically isolate the control circuit from the load circuit, providing safety. PIR (Passive Infrared) sensors detect motion by measuring changes in infrared radiation emitted by warm bodies. DHT22 sensors use a single-wire digital interface to report temperature and humidity with high accuracy.

Advertisement

Components & Requirements

12 components required for this project.

#ComponentPurposeQty
1Raspberry Pi 4 Model B (4GB)Central hub and serverx1
2Arduino Uno / NodeMCU ESP8266Peripheral device controllersx3
34-Channel 5V Relay ModuleSwitching AC loads (lights, fans)x2
4PIR Motion Sensor (HC-SR501)Occupancy detection in roomsx4
5DHT22 Temperature & Humidity SensorEnvironmental monitoringx3
6LDR (Light Dependent Resistor)Automatic lighting based on ambient lightx4
75V 10A Power SupplySystem powerx1
8MCP23017 I/O ExpanderExpanding GPIO pinsx1
9DS18B20 Waterproof Temp SensorOutdoor/water temperaturex2
10120dB BuzzerSecurity alarmx1
1116x2 LCD with I2C ModuleLocal status displayx1
12Jumper Wires, Breadboard, PCBCircuit connectionsxSet

Step-by-Step Implementation

Follow these 12 steps carefully.

1
System Architecture Design

Draw the complete block diagram showing the Raspberry Pi hub, Arduino nodes, relay modules, sensors, and cloud connectivity. Define which devices each Arduino controls and the MQTT topic structure. Document the WiFi network requirements and power distribution plan.

2
Setting Up Raspberry Pi as Hub

Install Raspberry Pi OS Lite. Install Mosquitto MQTT broker: sudo apt install mosquitto mosquitto-clients. Configure mosquitto.conf to allow remote connections on port 1883. Install Node-RED for visual automation flows: bash <(curl -sL https://raw.githubusercontent.com/node-red/linux-installers/master/deb/update-nodejs-and-nodered). Install Node-RED dashboard for the web UI.

3
Programming Arduino/ESP8266 Nodes

For each room's ESP8266, install PubSubClient and ArduinoJson libraries. Configure WiFi credentials and MQTT broker IP. Write code to subscribe to control topics (home/bedroom/light) and publish sensor data every 30 seconds. Each node controls 2–4 relay channels via GPIO HIGH/LOW signals.

4
Relay Module Wiring

Connect relay modules to ESP8266 GPIO pins (D1, D2, D3, D4). Wire the relay's COM terminal to the live wire of AC supply. Connect NC (Normally Closed) or NO (Normally Open) based on failsafe requirements. Ensure the relay board has proper isolation. Use 18-gauge wire for AC connections.

5
Sensor Integration

Connect PIR sensors to digital GPIO pins with 10kΩ pull-down resistors. Wire DHT22 sensors to digital pins with 4.7kΩ pull-up resistors on the data line. LDR sensors require a voltage divider with a 10kΩ fixed resistor feeding into an analog input pin (A0 on NodeMCU).

6
MQTT Communication Setup

Define a clear topic hierarchy: catbhome/[room]/[device]/[command]. Test topics using mosquitto_pub and mosquitto_sub from terminal. Configure QoS level 1 for critical commands. Set up retained messages for device state persistence. Configure Last Will and Testament (LWT) for offline device detection.

7
Node-RED Dashboard & Automation

Create a Node-RED flow for each room with MQTT input nodes, function nodes for logic, and dashboard UI elements (switches, gauges, charts). Implement time-based rules (turn off all lights at midnight). Add geofencing logic using phone GPS via the OwnTracks app. Create automation flows: if motion detected in kitchen for >2 mins, turn on exhaust fan.

8
Mobile App Development (Optional)

Use MIT App Inventor or Flutter to create a mobile app. Implement MQTT client in the app using HiveMQ's MQTT library. Create toggle buttons for each device, real-time sensor gauges, and scheduling features. Alternatively, use the Home Assistant or Blynk platform for ready-made app connectivity.

9
Security Implementation

Enable MQTT username/password authentication in mosquitto.conf. Generate SSL/TLS certificates using Let's Encrypt for encrypted communication. Implement API key validation for the web dashboard. Set up a firewall (UFW) on Raspberry Pi to limit access to required ports only.

10
Power Failure Handling

Program each ESP8266 to save last relay states to EEPROM. On power restart, read EEPROM and restore relay states. Add an Uninterruptible Power Supply (UPS) for the Raspberry Pi to maintain hub operation during brief outages. Implement watchdog timer on Arduino to auto-restart if program hangs.

11
Testing & Calibration

Test each relay independently using manual MQTT commands. Calibrate PIR sensitivity and delay using onboard potentiometers. Test DHT22 readings against a reference thermometer. Simulate network drops and verify device reconnection. Perform a 72-hour continuous operation test logging all events.

12
Final Integration & Documentation

Mount all components in a proper enclosure. Label all wires and connections. Create a wiring diagram in Fritzing. Document all MQTT topics, pin mappings, and WiFi credentials in a secure location. Record a demo video of all features working.

Code & Implementation

Core code for esp8266_node.ino:

esp8266_node.ino C/C++
#include <ESP8266WiFi.h> #include <PubSubClient.h> #include <DHT.h> #include <EEPROM.h>   const char* SSID       = "YourWiFiSSID"; const char* PASS       = "YourWiFiPass"; const char* MQTT_HOST  = "192.168.1.100";   const int   MQTT_PORT  = 1883; const char* CLIENT_ID  = "bedroom-node";   #define RELAY_1 D1    #define RELAY_2 D2    #define PIR_PIN D5 #define DHT_PIN D6 #define DHT_TYPE DHT22  DHT dht(DHT_PIN, DHT_TYPE); WiFiClient espClient; PubSubClient mqtt(espClient);   bool light_on = false; bool fan_on   = false;   void callback(char* topic, byte* payload, unsigned int len) {   String msg = "";   for (int i = 0; i < len; i++) msg += (char)payload[i];    String t = String(topic);   if (t == "catbhome/bedroom/light") {     light_on = (msg == "ON");     digitalWrite(RELAY_1, light_on ? LOW : HIGH);      EEPROM.write(0, light_on ? 1 : 0);     EEPROM.commit();   }   if (t == "catbhome/bedroom/fan") {     fan_on = (msg == "ON");     digitalWrite(RELAY_2, fan_on ? LOW : HIGH);     EEPROM.write(1, fan_on ? 1 : 0);     EEPROM.commit();   } }  void setup() {   EEPROM.begin(16);   pinMode(RELAY_1, OUTPUT); pinMode(RELAY_2, OUTPUT);   pinMode(PIR_PIN, INPUT);      light_on = EEPROM.read(0) == 1;   fan_on   = EEPROM.read(1) == 1;   digitalWrite(RELAY_1, light_on ? LOW : HIGH);   digitalWrite(RELAY_2, fan_on   ? LOW : HIGH);    WiFi.begin(SSID, PASS);   while (WiFi.status() != WL_CONNECTED) delay(500);    mqtt.setServer(MQTT_HOST, MQTT_PORT);   mqtt.setCallback(callback);   dht.begin(); }  unsigned long lastSensorPublish = 0;  void loop() {   if (!mqtt.connected()) {     mqtt.connect(CLIENT_ID);     mqtt.subscribe("catbhome/bedroom/light");     mqtt.subscribe("catbhome/bedroom/fan");   }   mqtt.loop();       if (millis() - lastSensorPublish > 30000) {     float temp = dht.readTemperature();     float hum  = dht.readHumidity();     if (!isnan(temp)) {       mqtt.publish("catbhome/bedroom/temp", String(temp, 1).c_str());       mqtt.publish("catbhome/bedroom/humidity", String(hum, 1).c_str());     }          bool motion = digitalRead(PIR_PIN);     mqtt.publish("catbhome/bedroom/motion", motion ? "1" : "0");     lastSensorPublish = millis();   } }

Testing & Troubleshooting

Begin testing by verifying MQTT connectivity using the mosquitto_sub command on the Raspberry Pi terminal. Publish test commands like mosquitto_pub -h localhost -t "catbhome/bedroom/light" -m "ON" and verify the relay clicks. Use a multimeter to confirm relay output switching. Check DHT22 readings in the Node-RED dashboard and compare against a reference thermometer — acceptable tolerance is ±0.5°C. Test PIR sensors by walking in front of them and verifying MQTT payload changes to "1". Stress-test the system by sending 100 rapid commands and checking for missed messages (QoS 1 should guarantee delivery). Test WiFi reconnection by unplugging and replugging the router. Verify EEPROM state restoration by cutting power and restoring — all relays should return to their last known state. Run the system for 48 hours continuously logging all MQTT traffic to identify any memory leaks or connection drops.

!
Troubleshooting Tips

Verify power voltages, check ground connections, use serial monitor for debug.

Real-World Applications

*Residential smart homes and apartments
*Hotel room automation systems
*Office building energy management
*Hospital ward environment control
*Greenhouse climate control
*Elderly care monitoring systems
*Industrial facility management
*Rental property remote management

Extensions & Next Steps

  • Add voice control using Amazon Alexa or Google Home integration
  • Integrate AI-based energy optimization using occupancy prediction
  • Add solar panel monitoring and automatic load shifting
  • Implement face recognition for keyless door entry
  • Add water leak detection sensors with automatic valve shutoff
  • Build a custom PCB to replace the breadboard prototype

Interactive Playground

Coming Soon

An interactive simulator will be available here — simulate circuits and run code in-browser without hardware.

Frequently Asked Questions

Can this system work without internet connection?
Yes! The MQTT broker runs locally on the Raspberry Pi, so all automation rules work on the local WiFi network even without internet. Internet connectivity is only needed for remote access from outside the home or for cloud-based voice assistants.
How many devices can this system control?
With a single Raspberry Pi hub and multiple ESP8266 nodes, you can control theoretically unlimited devices. Each ESP8266 can manage up to 8 relay channels. A typical home can run 5–10 nodes comfortably, giving you control of 40–80 individual appliance circuits.
Is it safe to control 220V AC appliances with this system?
Yes, when proper safety precautions are followed. The relay module provides electrical isolation between the 3.3V control circuit and the 220V load circuit. Always use optoisolated relay boards, rated wires (18 AWG minimum), proper connectors, and enclose all high-voltage connections in a safely rated enclosure. Consider hiring a licensed electrician for final AC wiring.
What happens if the WiFi goes down?
Each ESP8266 stores relay states in EEPROM and the Last Will and Testament (LWT) feature in MQTT marks devices as offline. Devices retain their last state during WiFi outages. The system automatically reconnects and re-syncs when connectivity is restored.
Can I use this with existing home wiring without rewiring?
In most cases, yes. Relay modules can be inserted in line with existing light switches and appliance circuits. For lights, you typically need to run a neutral wire to the switch box if not already present. Smart plug adapters can be used for appliances without any wiring modification.
Advertisement