Content is user-generated and unverified.

Smart Home Automation Prototype - Complete Student Guide

Project Overview

This project demonstrates a comprehensive home automation system using ESP32 microcontroller that can control lighting, monitor security, track environmental conditions, and manage appliances remotely via a mobile app.

Key Features

  • Smart Lighting Control: Automated LED/bulb control with manual override
  • Security System: Motion detection with alerts and notifications
  • Environmental Monitoring: Temperature, humidity, and air quality tracking
  • Appliance Control: Remote control of fans, heaters, and other devices
  • Mobile App Integration: Full control via smartphone application
  • Web Dashboard: Real-time monitoring and control interface

Components Required

Main Controller

  • ESP32 Development Board (38-pin version recommended)
    • Price: LKR 2,500 - 3,500
    • Features: WiFi + Bluetooth, dual-core processor

Sensors

  1. PIR Motion Sensor (HC-SR501)
    • Price: LKR 280 - 400
    • Purpose: Motion detection for security
  2. DHT22 Temperature & Humidity Sensor
    • Price: LKR 800 - 1,200
    • Purpose: Environmental monitoring
  3. LDR (Light Dependent Resistor)
    • Price: LKR 50 - 100
    • Purpose: Ambient light detection
  4. MQ-2 Gas Sensor (Optional)
    • Price: LKR 600 - 800
    • Purpose: Gas leak detection

Output Devices

  1. Relay Module (4-channel)
    • Price: LKR 800 - 1,200
    • Purpose: Control high-voltage appliances
  2. LED Strip/Bulbs
    • Price: LKR 500 - 1,500
    • Purpose: Smart lighting
  3. Servo Motor SG90
    • Price: LKR 400 - 600
    • Purpose: Automated door/window control
  4. Buzzer
    • Price: LKR 100 - 200
    • Purpose: Alarm system

Additional Components

  • Breadboard/PCB: LKR 200 - 500
  • Jumper Wires: LKR 300 - 500
  • Resistors Set: LKR 200 - 400
  • Power Supply (5V 2A): LKR 800 - 1,200
  • Enclosure Box: LKR 500 - 1,000

Total Budget Estimate

CategoryCost Range (LKR)
Main Controller2,500 - 3,500
Sensors1,730 - 2,500
Output Devices1,800 - 3,300
Additional Components1,800 - 3,600
Total Project Cost7,830 - 12,900

Note: Prices may vary based on supplier and quality. Budget suitable for student projects.


Step-by-Step Implementation

Phase 1: Hardware Setup

Step 1: ESP32 Setup

  1. Install ESP32 board package in Arduino IDE
  2. Connect ESP32 to computer via USB cable
  3. Test basic connectivity with LED blink program

Step 2: Sensor Connections

PIR Motion Sensor:
- VCC → 3.3V
- GND → GND
- OUT → GPIO 13

DHT22 Temperature Sensor:
- VCC → 3.3V
- GND → GND
- DATA → GPIO 14

LDR (Light Sensor):
- One end → 3.3V
- Other end → GPIO 35 (ADC pin)
- 10kΩ resistor between GPIO 35 and GND

Step 3: Output Device Connections

Relay Module:
- VCC → 5V
- GND → GND
- IN1 → GPIO 25 (Light Control)
- IN2 → GPIO 26 (Fan Control)
- IN3 → GPIO 27 (Heater Control)
- IN4 → GPIO 32 (Door Lock)

LED Strip:
- Connect through relay module for switching
- Ensure proper voltage rating

Servo Motor:
- VCC → 5V
- GND → GND
- Signal → GPIO 18

Buzzer:
- Positive → GPIO 19
- Negative → GND

Phase 2: Software Development

Step 1: Arduino IDE Setup

  1. Download and install Arduino IDE
  2. Add ESP32 board support:
    • Go to File → Preferences
    • Add: https://dl.espressif.com/dl/package_esp32_index.json
    • Install ESP32 boards via Board Manager

Step 2: Required Libraries

Install these libraries via Library Manager:

  • WiFi (built-in)
  • WebServer (built-in)
  • DHT sensor library
  • Servo library
  • ArduinoJson
  • PubSubClient (for MQTT)
  • Blynk library

Step 3: Main Code Structure

cpp
#include <WiFi.h>
#include <WebServer.h>
#include <DHT.h>
#include <Servo.h>
#include <ArduinoJson.h>

// Network credentials
const char* ssid = "YOUR_WIFI_SSID";
const char* password = "YOUR_WIFI_PASSWORD";

// Pin definitions
#define PIR_PIN 13
#define DHT_PIN 14
#define LDR_PIN 35
#define RELAY1_PIN 25  // Light
#define RELAY2_PIN 26  // Fan
#define RELAY3_PIN 27  // Heater
#define RELAY4_PIN 32  // Door Lock
#define SERVO_PIN 18
#define BUZZER_PIN 19

// Initialize components
DHT dht(DHT_PIN, DHT22);
Servo doorServo;
WebServer server(80);

// Global variables
bool lightState = false;
bool fanState = false;
bool heaterState = false;
bool doorLocked = true;
bool motionDetected = false;
float temperature = 0;
float humidity = 0;
int lightLevel = 0;

void setup() {
  Serial.begin(115200);
  
  // Initialize pins
  pinMode(PIR_PIN, INPUT);
  pinMode(LDR_PIN, INPUT);
  pinMode(RELAY1_PIN, OUTPUT);
  pinMode(RELAY2_PIN, OUTPUT);
  pinMode(RELAY3_PIN, OUTPUT);
  pinMode(RELAY4_PIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  
  // Initialize components
  dht.begin();
  doorServo.attach(SERVO_PIN);
  
  // Connect to WiFi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  
  Serial.println("WiFi connected!");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  
  // Setup web server routes
  setupServerRoutes();
  server.begin();
}

void loop() {
  server.handleClient();
  
  // Read sensors
  readSensors();
  
  // Check for motion
  checkMotion();
  
  // Automatic light control based on ambient light
  autoLightControl();
  
  delay(1000);
}

void readSensors() {
  temperature = dht.readTemperature();
  humidity = dht.readHumidity();
  lightLevel = analogRead(LDR_PIN);
  motionDetected = digitalRead(PIR_PIN);
}

void checkMotion() {
  if (motionDetected) {
    Serial.println("Motion detected!");
    // Trigger security alert
    securityAlert();
  }
}

void autoLightControl() {
  if (lightLevel < 500 && !lightState) {
    // Turn on light automatically in dark conditions
    digitalWrite(RELAY1_PIN, HIGH);
    lightState = true;
  }
}

void securityAlert() {
  // Sound buzzer
  digitalWrite(BUZZER_PIN, HIGH);
  delay(1000);
  digitalWrite(BUZZER_PIN, LOW);
  
  // Send notification (implement mobile app notification)
  sendNotification("Motion detected in your home!");
}

void setupServerRoutes() {
  // Main dashboard
  server.on("/", handleRoot);
  
  // API endpoints
  server.on("/api/status", handleStatus);
  server.on("/api/control", handleControl);
  server.on("/api/sensors", handleSensors);
}

void handleRoot() {
  String html = generateDashboard();
  server.send(200, "text/html", html);
}

void handleStatus() {
  StaticJsonDocument<200> doc;
  doc["light"] = lightState;
  doc["fan"] = fanState;
  doc["heater"] = heaterState;
  doc["door"] = doorLocked;
  doc["motion"] = motionDetected;
  
  String response;
  serializeJson(doc, response);
  server.send(200, "application/json", response);
}

void handleControl() {
  if (server.hasArg("device") && server.hasArg("state")) {
    String device = server.arg("device");
    bool state = server.arg("state") == "true";
    
    if (device == "light") {
      digitalWrite(RELAY1_PIN, state ? HIGH : LOW);
      lightState = state;
    } else if (device == "fan") {
      digitalWrite(RELAY2_PIN, state ? HIGH : LOW);
      fanState = state;
    } else if (device == "heater") {
      digitalWrite(RELAY3_PIN, state ? HIGH : LOW);
      heaterState = state;
    } else if (device == "door") {
      doorServo.write(state ? 0 : 90);
      doorLocked = state;
    }
    
    server.send(200, "text/plain", "OK");
  } else {
    server.send(400, "text/plain", "Missing parameters");
  }
}

void handleSensors() {
  StaticJsonDocument<200> doc;
  doc["temperature"] = temperature;
  doc["humidity"] = humidity;
  doc["light_level"] = lightLevel;
  doc["motion"] = motionDetected;
  
  String response;
  serializeJson(doc, response);
  server.send(200, "application/json", response);
}

String generateDashboard() {
  String html = R"(
<!DOCTYPE html>
<html>
<head>
    <title>Smart Home Dashboard</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background: #f0f0f0; }
        .container { max-width: 800px; margin: 0 auto; }
        .card { background: white; padding: 20px; margin: 10px 0; border-radius: 10px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); }
        .sensor-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 15px; }
        .control-btn { padding: 10px 20px; margin: 5px; border: none; border-radius: 5px; cursor: pointer; }
        .on { background: #4CAF50; color: white; }
        .off { background: #f44336; color: white; }
        .sensor-value { font-size: 24px; font-weight: bold; color: #333; }
        .sensor-label { color: #666; margin-bottom: 5px; }
        h1 { color: #333; text-align: center; }
        h2 { color: #555; border-bottom: 2px solid #ddd; padding-bottom: 10px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>🏠 Smart Home Dashboard</h1>
        
        <div class="card">
            <h2>📊 Sensor Readings</h2>
            <div class="sensor-grid">
                <div>
                    <div class="sensor-label">Temperature</div>
                    <div class="sensor-value" id="temp">--°C</div>
                </div>
                <div>
                    <div class="sensor-label">Humidity</div>
                    <div class="sensor-value" id="humidity">--%</div>
                </div>
                <div>
                    <div class="sensor-label">Light Level</div>
                    <div class="sensor-value" id="light">--</div>
                </div>
                <div>
                    <div class="sensor-label">Motion</div>
                    <div class="sensor-value" id="motion">--</div>
                </div>
            </div>
        </div>
        
        <div class="card">
            <h2>🎛️ Device Control</h2>
            <button class="control-btn" id="lightBtn" onclick="toggleDevice('light')">💡 Light</button>
            <button class="control-btn" id="fanBtn" onclick="toggleDevice('fan')">🌀 Fan</button>
            <button class="control-btn" id="heaterBtn" onclick="toggleDevice('heater')">🔥 Heater</button>
            <button class="control-btn" id="doorBtn" onclick="toggleDevice('door')">🚪 Door Lock</button>
        </div>
    </div>

    <script>
        function updateSensors() {
            fetch('/api/sensors')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('temp').textContent = data.temperature + '°C';
                    document.getElementById('humidity').textContent = data.humidity + '%';
                    document.getElementById('light').textContent = data.light_level;
                    document.getElementById('motion').textContent = data.motion ? 'Detected' : 'None';
                });
        }

        function updateStatus() {
            fetch('/api/status')
                .then(response => response.json())
                .then(data => {
                    updateButtonState('lightBtn', data.light);
                    updateButtonState('fanBtn', data.fan);
                    updateButtonState('heaterBtn', data.heater);
                    updateButtonState('doorBtn', data.door);
                });
        }

        function updateButtonState(btnId, state) {
            const btn = document.getElementById(btnId);
            btn.className = 'control-btn ' + (state ? 'on' : 'off');
        }

        function toggleDevice(device) {
            fetch('/api/status')
                .then(response => response.json())
                .then(data => {
                    const currentState = data[device];
                    const newState = !currentState;
                    
                    fetch(`/api/control?device=${device}&state=${newState}`)
                        .then(() => updateStatus());
                });
        }

        // Update data every 2 seconds
        setInterval(() => {
            updateSensors();
            updateStatus();
        }, 2000);

        // Initial load
        updateSensors();
        updateStatus();
    </script>
</body>
</html>
)";
  return html;
}

void sendNotification(String message) {
  // Implement notification system
  // Can use Firebase, Pushover, or custom notification service
  Serial.println("Notification: " + message);
}

Phase 3: Mobile App Development

Option 1: Blynk App (Recommended for beginners)

  1. Download Blynk app from Play Store/App Store
  2. Create new project and get Auth Token
  3. Add widgets for:
    • Temperature/Humidity display
    • Button widgets for device control
    • LED indicators for status
    • Notification widget for alerts

Option 2: MIT App Inventor

  1. Create account at http://ai2.appinventor.mit.edu
  2. Design interface with:
    • Buttons for device control
    • Labels for sensor readings
    • Web component for HTTP requests
  3. Use blocks to connect to ESP32 web server

Option 3: Flutter/React Native (Advanced)

For custom mobile app development with professional features.

Phase 4: Testing and Deployment

Testing Checklist

  • WiFi connectivity
  • Sensor readings accuracy
  • Device control functionality
  • Mobile app connectivity
  • Security alerts
  • Automatic light control
  • Web dashboard responsiveness

Deployment Steps

  1. Set up permanent power supply
  2. Install in suitable enclosure
  3. Mount sensors in appropriate locations
  4. Configure WiFi credentials
  5. Set up mobile app
  6. Test all functionalities
  7. Create user manual

Software Requirements

Development Environment

  • Arduino IDE (Version 1.8.x or 2.x)
  • ESP32 Board Package
  • USB Driver (CP2102 or CH340)

Libraries Required

WiFi - Built-in
WebServer - Built-in
DHT sensor library - by Adafruit
Servo - Built-in
ArduinoJson - by Benoit Blanchon
PubSubClient - by Nick O'Leary
Blynk - by Blynk

Mobile App Options

  1. Blynk - Easiest, drag-and-drop interface
  2. MIT App Inventor - Educational, block-based programming
  3. Flutter - Professional cross-platform development
  4. React Native - JavaScript-based mobile development

Circuit Diagram

ESP32 Pin Connections:
=====================
GPIO 13 ← PIR Motion Sensor (OUT)
GPIO 14 ← DHT22 Temperature Sensor (DATA)
GPIO 35 ← LDR Light Sensor (analog)
GPIO 25 → Relay 1 (Light Control)
GPIO 26 → Relay 2 (Fan Control)
GPIO 27 → Relay 3 (Heater Control)
GPIO 32 → Relay 4 (Door Lock)
GPIO 18 → Servo Motor (Signal)
GPIO 19 → Buzzer (Positive)

Power Connections:
=================
3.3V → PIR VCC, DHT22 VCC, LDR (one end)
5V → Relay VCC, Servo VCC
GND → All component grounds

Mobile App Control Features

Core Features

  1. Device Control
    • Toggle lights on/off
    • Control fan speed
    • Adjust heater temperature
    • Lock/unlock doors
  2. Monitoring
    • Real-time temperature readings
    • Humidity levels
    • Motion detection status
    • Light sensor readings
  3. Automation
    • Schedule device operations
    • Set temperature thresholds
    • Automatic light control
    • Security mode activation
  4. Notifications
    • Motion detection alerts
    • Temperature warnings
    • Device status changes
    • System connectivity status

App Development Platforms

Blynk (Recommended for Students)

  • Pros: Easy to use, no coding required, built-in widgets
  • Cons: Limited customization, requires internet
  • Cost: Free tier available
  • Setup Time: 30 minutes

MIT App Inventor

  • Pros: Educational, visual programming, completely free
  • Cons: Basic UI, limited advanced features
  • Cost: Completely free
  • Setup Time: 2-3 hours

Flutter

  • Pros: Professional look, cross-platform, highly customizable
  • Cons: Requires programming knowledge
  • Cost: Free
  • Setup Time: 1-2 weeks

Reference Resources

Online Tutorials

  1. ESP32 Official Documentation
  2. Arduino IDE ESP32 Setup
  3. Home Automation Projects

YouTube Channels

  1. Random Nerd Tutorials
  2. TechStudyCell
  3. GreatScott!
  4. DroneBot Workshop

Sri Lankan Suppliers

  1. Duino.lk
  2. LK Tronics
  3. Alphatronic
  4. Microchip.lk

Books and Documentation

  1. "ESP32 Projects Book" - Available online
  2. "Arduino Home Automation" - Multiple authors
  3. Official ESP32 Programming Guide - Espressif

Project Timeline

Week 1: Planning and Component Procurement

  • Finalize project scope
  • Order components
  • Set up development environment
  • Study circuit diagrams

Week 2: Basic Hardware Setup

  • Assemble basic circuit
  • Test ESP32 connectivity
  • Test individual sensors
  • Basic LED control

Week 3: Software Development

  • Write sensor reading code
  • Implement web server
  • Create basic dashboard
  • Test device control

Week 4: Advanced Features

  • Add automation features
  • Implement security system
  • Create mobile app
  • Test integration

Week 5: Testing and Documentation

  • Comprehensive testing
  • Bug fixes
  • Documentation
  • Presentation preparation

Troubleshooting Guide

Common Issues and Solutions

  1. ESP32 Not Connecting to WiFi
    • Check SSID and password
    • Verify WiFi signal strength
    • Try different WiFi bands (2.4GHz vs 5GHz)
  2. Sensors Not Reading Correctly
    • Check wiring connections
    • Verify power supply voltage
    • Test with multimeter
  3. Relay Not Switching
    • Check relay module power supply
    • Verify logic voltage levels
    • Test with LED first
  4. Mobile App Not Connecting
    • Check ESP32 IP address
    • Verify network connectivity
    • Test with web browser first

Safety Precautions

  • Never work with mains voltage without proper supervision
  • Use proper fuses and circuit breakers
  • Ensure proper grounding
  • Test in safe environment first

Future Enhancements

Possible Upgrades

  1. Voice Control Integration
    • Amazon Alexa compatibility
    • Google Assistant integration
  2. Advanced Security
    • Camera integration
    • Facial recognition
    • SMS alerts
  3. Energy Monitoring
    • Power consumption tracking
    • Cost analysis
    • Energy-saving recommendations
  4. Machine Learning
    • Predictive automation
    • Usage pattern analysis
    • Intelligent scheduling

Scalability Options

  • Multiple room control
  • Centralized monitoring
  • Cloud data storage
  • Remote access via internet

Conclusion

This smart home automation prototype provides a comprehensive foundation for understanding IoT concepts, embedded programming, and mobile app development. The project is designed to be educational while producing a functional system that can be extended and improved.

The estimated budget of LKR 7,830 - 12,900 makes this project accessible to students while providing hands-on experience with real-world technologies. The modular design allows for incremental development and testing.

Key Learning Outcomes:

  • Microcontroller programming
  • Sensor integration
  • Web server development
  • Mobile app creation
  • IoT system design
  • Network programming

Project Deliverables:

  • Functional hardware prototype
  • Complete source code
  • Mobile application
  • Documentation
  • Demonstration video

This project serves as an excellent foundation for understanding modern IoT systems and can be expanded into more complex automation solutions.


Document Version: 1.0
Last Updated: July 2025
Target Audience: Engineering Students, Sri Lanka

Content is user-generated and unverified.
    Smart Home Automation Prototype - Complete Guide | Claude