prabinrajupreti
Published

IoT Based Home Automation

In this tutorial, I am going to teach you about IoT based Home Automation using the ESP8266 WiFi module.

IntermediateWork in progress30,007
IoT Based Home Automation

Things used in this project

Hardware components

Arduino UNO
Arduino UNO
×1
Power Relay, SPDT
Power Relay, SPDT
×4
Slide Switch, SPDT-CO
Slide Switch, SPDT-CO
×4
Router
×1
ESP8266 ESP-01
Espressif ESP8266 ESP-01
×1
Test Accessory, AC Power Adaptor
Test Accessory, AC Power Adaptor
×1

Story

Read more

Custom parts and enclosures

House Model

This is a model of the house. in where we are installing our system.

Schematics

Circuit Diagram

Code

Arduino Code

Arduino
#include <SoftwareSerial.h>

SoftwareSerial esp8266(2,3);

#define serialCommunicationSpeed 9600
#define DEBUG true
//#define STATUS = 0

//int checkStOne = 0;
//int checkStTwo = 0;
//int checkStThree = 1;
//int checkStFour = 1;


//int detectorOne = 9;
//int detectorTwo = 10;
//int detectorThree = 11;
//int detectorFour = 12;

int lightOne = 6;
int lightTwo = 7;
int lightThree = 8;
int lightFour = 9;

int indicator = 13;


void setup()
{
//  pinMode(detectorOne,INPUT);
//  pinMode(detectorTwo,INPUT);
//  pinMode(detectorThree,INPUT);
//  pinMode(detectorFour,INPUT);

  
//  digitalWrite(detectorOne,LOW);
//  digitalWrite(detectorTwo,LOW);
//  digitalWrite(detectorThree,LOW);
//  digitalWrite(detectorFour,LOW);
  
  pinMode(lightOne,OUTPUT);
  pinMode(lightTwo,OUTPUT);
  pinMode(lightThree,OUTPUT);
  pinMode(lightFour,OUTPUT);
  
  pinMode(indicator,OUTPUT);

  
  digitalWrite(lightOne,HIGH);
  digitalWrite(lightTwo,HIGH);
  digitalWrite(lightThree,HIGH);
  digitalWrite(lightFour,HIGH);
  
  digitalWrite(indicator,HIGH);

  
  Serial.begin(serialCommunicationSpeed);
  esp8266.begin(serialCommunicationSpeed);
  
  InitWifiModule();
//  checkCircuitStatus();
  
  digitalWrite(indicator,LOW);
  delay(200);
}
void loop()
{
  if(esp8266.available())
  {
//    Serial.println("i got something");
    delay(500);
    if(esp8266.find("+IPD,"))
    {
      delay(500);
      int connectionId = esp8266.read()-48;
      esp8266.find("pin=");
      int pinNumber = (esp8266.read()-48);
//      pinNumber = pinNumber + (esp8266.read()-48);
      int statusLed =(esp8266.read()-48);
      delay(500);
      String responseData = "AT+CIPSEND=";
      responseData += connectionId;
      responseData += ",1\r\n";
      Serial.println(responseData);
      sendData(responseData , 800, DEBUG);
      delay(100);
      sendData(pinNumber+"\r\n",500,DEBUG);
      delay(100);
      digitalWrite(pinNumber, statusLed);
      String closeCommand = "AT+CIPCLOSE=";
      closeCommand+=connectionId;
      closeCommand+="\r\n";
      sendData(closeCommand,500,DEBUG);            
    }
  }
//  if(digitalRead(detectorOne) != checkStOne || digitalRead(detectorTwo) != checkStTwo || digitalRead(detectorThree) != checkStThree || digitalRead(detectorFour) != checkStFour){
//    Serial.println("i am inside loop");
//    if(digitalRead(detectorOne) != checkStOne){
//      checkStOne = digitalRead(detectorOne);
//      sendStToDatabase(detectorOne, checkStOne);
//    }
//    if(digitalRead(detectorTwo) != checkStTwo){
//      checkStTwo = digitalRead(detectorTwo);
//      sendStToDatabase(detectorTwo , checkStTwo);
//    }
//    if(digitalRead(detectorThree) != checkStThree){
//      checkStThree = digitalRead(detectorThree);
//      sendStToDatabase(detectorThree , checkStThree);
//    }
//    if(digitalRead(detectorFour) != checkStFour){
//      checkStFour = digitalRead(detectorFour);
//      sendStToDatabase(detectorFour , checkStFour);
//    }
//    
//  }
//  else{
//    Serial.println("I AM NOT OK, ok?");
//    Serial.println(digitalRead(detectorTwo));  
//    delay(1000);
//  }
}


//    int changeOccured(){
//      int static StatusOfDetectorOne = 0;      
//      int static StatusOfDetectoTwo = 0;      
//      int static StatusOfDetectorThree = 0;      
//      int static StatusOfDetectorFour = 0;
//      if(digitalRead(detectorOne) != StatusOfDetectorOne){
//        StatusOfDetectorOne = digitalRead(detectorOne);
//      }
//      if(digitalRead(detectorTwo) != StatusOfDetectoTwo){
//        StatusOfDetectoTwo = digitalRead(detectorTwo);
//      }
//      if(digitalRead(detectorThree) != StatusOfDetectorThree){
//        StatusOfDetectorThree = digitalRead(detectorThree);
//      }
//      if(digitalRead(detectorFour) != StatusOfDetectorFour){
//        StatusOfDetectorFour = digitalRead(detectorFour);
//      }
//      
//    }

void sendData(String command, const int timeout, boolean debug){
    String response = "";          
    esp8266.print(command);
    long int time = millis();
    while( (time+timeout) > millis()){
      while(esp8266.available()){
        char c = esp8266.read();
        response+=c;
      }
    }
    if(DEBUG){
      Serial.print(response);
    }
//    return response;
}
void InitWifiModule(){
  sendData("AT+RST\r\n", 1000, DEBUG);
  delay(1000);
  sendData("AT+CWMODE=1\r\n", 1000, DEBUG);
  delay (500);
  sendData("AT+CWJAP=\"your SSID\",\"password\"\r\n", 10000, DEBUG);
  delay (1000);
  sendData("AT+CIFSR\r\n", 1000, DEBUG);
  delay (1000);
  sendData("AT+CIPMUX=1\r\n", 500, DEBUG);
  delay (1000);
  sendData("AT+CIPSERVER=1,80\r\n", 1000, DEBUG);
  delay(500);
}
//void checkCircuitStatus(){
//  if(digitalRead(detectorOne)){
//    checkStOne = 1;
//    sendStToDatabase(detectorOne, checkStOne);
//  }
//  if(digitalRead(detectorTwo)){
//    checkStTwo = 1;
//    sendStToDatabase(detectorTwo , checkStTwo);
//  }
//  if(digitalRead(detectorThree)){
//    checkStThree = 1;
//    sendStToDatabase(detectorThree , checkStThree);
//  }
//  if(digitalRead(detectorFour)){
//    checkStFour = 1;
//    sendStToDatabase(detectorFour , checkStFour);
//  }
//}
//void sendStToDatabase(int detector, int checkSt){
//  Serial.println("i am here");
//  Serial.println(detector);
//  Serial.println(checkSt);
//  
//}

home.html

HTML
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="../bootstrap-4.3.1/dist/css/bootstrap.min.css">
  <script src="../bootstrap-4.3.1/dist/js/jquery.min.js"></script>
  <script src="script.js"></script>

  <title>IoT Home Automation</title>
</head>

<body onload="initApp()">
  <div class="">
    <nav class="navbar navbar-expand-md bg-dark navbar-dark">
      <!-- Brand -->
      <a class="navbar-brand" href="home.html">IoT Home Automation</a>

      <!-- Toggler/collapsibe Button -->
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
        <span class="navbar-toggler-icon"></span>
      </button>

      <!-- Navbar links -->
      <div class="collapse navbar-collapse" id="collapsibleNavbar">
        <ul class="navbar-nav">
          <!-- <li class="nav-item">
            <a class="nav-link" href="dashboard.html">Dashboard</a>
          </li>
          <li class="nav-item"> -->
            <a class="nav-link" href="control.html">Controller</a>
          </li>
        </ul>
      </div>
    </nav>
    <br>
    <img src="img/khec.png" style="padding-top:20px; padding-bottom: 50px;" class="img img-fluid rounded mx-auto d-block"
      alt="Khwopa Engineering College">
    <div class="col">
      <h3 class="text-center">Welcome to IoT Home Automation</h3>
    </div>
    <div style="padding-top:20px;" class="container col">
      <ulc class="list-group">
        <li class="list-group-item active">Team Members:</li>
        <li class="font-weight-bold list-group-item d-flex justify-content-between align-items-center">Prabin Raj Upreti
          <span class="badge badge-primary badge-pill">750421</span>
        </li>
        <li class="list-group-item d-flex justify-content-between align-items-center">Erina Sharma
          <span class="badge badge-primary badge-pill">750411</span></li>
        <li class="list-group-item d-flex justify-content-between align-items-center">Parash Sapkota
          <span class="badge badge-primary badge-pill">750419</span></li>
        <li class="list-group-item d-flex justify-content-between align-items-center">Sajan Duwal
          <span class="badge badge-primary badge-pill">750425</span></li>
        </ul>
    </div>
    <script src="../bootstrap-4.3.1/dist/js/bootstrap.min.js"></script>
</body>

</html>

script.js

JavaScript
function initApp() {
  // var xhttp = new XMLHttpRequest();
  // xhttp.onreadystatechange = function() {
  //   if (this.readyState == 4 && this.status == 200) {
  //     // console.log(this.responseText);
  //   }
  // };
  // xhttp.open("GET", "../server/server.php", true);
  // xhttp.send();
}
function sendRequest(id) {
  // var res;
  // var paramg;
  document.getElementById(id).classList.remove('btn-primary');
  document.getElementById(id).classList.add('btn-warning');
  document.getElementsByClassName("get_id")[0].disabled = true;
  document.getElementsByClassName("get_id")[1].disabled = true;
  document.getElementsByClassName("get_id")[2].disabled = true;
  document.getElementsByClassName("get_id")[3].disabled = true;
  var xhttp = new XMLHttpRequest();
    //   if(this.readyState == 0){
    //     console.log("0: request not initialized");
    //   }
    //   if(this.readyState == 1){
    //     console.log("1: server connection established");  
    //   }
    //   if(this.readyState == 2){
    //     console.log("2: request received");  
    //   }
    //   if(this.readyState == 3){
    //     console.log("3: processing request");  
    //   }
    //   if(this.readyState == 4){
    //     console.log("4: request finished and response is ready");  
    //   }
    // res = this.responseText;
    // if (this.readyStatus == 4) {
    //   alert(res);
    // }
  // }

  xhttp.open("GET", "http://192.168.1.100:80?pin=" + id, true);
  // xhttp.setRequestHeader("Access-Control-Allow-Headers","*");
  // xhttp.setRequestHeader("Origin", "*");
  // xhttp.setRequestHeader("Access-Control-Allow-Methods", "GET, POST,PUT");
  // xhttp.setRequestHeader('Access-Control-Allow-Credential','true');
  xhttp.send();
  // alert('Sending Request to server!!');
  setTimeout(function(){
    document.getElementById(id).classList.remove('btn-warning');
    document.getElementById(id).classList.add('btn-primary');
    document.getElementsByClassName("get_id")[0].disabled = false;
    document.getElementsByClassName("get_id")[1].disabled = false;
    document.getElementsByClassName("get_id")[2].disabled = false;
    document.getElementsByClassName("get_id")[3].disabled = false;
    if (id % 2 == 0) {
      document.getElementById(id).id = parseInt(id) + 1;
    }
    if (id % 2 != 0) {
      document.getElementById(id).id = parseInt(id) - 1;
    }

  },4000);
  return;

}
// function sendToArduino(id) {

//     var xhttp = new XMLHttpRequest()
//     xhttp.open("GET", "http://10.10.5.101:80/?pin=" + id, false);
//     xhttp.send();
// }

control.html

HTML
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="../bootstrap-4.3.1/dist/css/bootstrap.min.css">
  <script src="../bootstrap-4.3.1/dist/js/jquery.min.js"></script>
  <script src="script.js"></script>
  <title>IoT Home Automation</title>
</head>

<body>
    <nav class="navbar navbar-expand-md bg-dark navbar-dark">
      <a class="navbar-brand" href="home.html">IoT Home Automation</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
        <span class="navbar-toggler-icon"></span>
      </button>
      <div class="collapse navbar-collapse" id="collapsibleNavbar">
        <ul class="navbar-nav">
          <!-- <li class="nav-item">
            <a class="nav-link" href="dashboard.html">Dashboard</a>
          </li> -->
          <li class="nav-item">
            <a class="nav-link" href="control.html">Controller</a>
          </li>
        </ul>
      </div>
    </nav>
    <div class="container">
      <h5 style="padding-top: 15px;" class="h5 text-left">Home/Controller</h5><hr>

    <div class="row">
      <div class=" col-sm-12 col-md-12 text-center">
        <h3>Turn ON/OFF</h3>
      </div>
      <div style="padding: 20px;" class="col-6 col-sm-6">
        <h2 style="padding-bottom: 50px;" class="text-center">AC</h2>
        <button id="60" class="get_id btn btn-lg btn-block btn-primary" onclick="sendRequest(this.id)">ON/OFF</button>
      </div>
      <div style="padding: 20px;" class="col-6 col-sm-6">
        <h2 style="padding-bottom: 50px;" class="text-center">Light 1</h2>
        <button id="70" class="get_id btn btn-lg btn-block btn-primary" onclick="sendRequest(this.id)">ON/OFF</button>
      </div>
      <div style="padding: 20px;" class="col-6 col-sm-6">
        <h2 style="padding-bottom: 50px;" class="text-center">Light 2</h2>
        <button id="80" class="get_id btn btn-lg btn-block btn-primary" onclick="sendRequest(this.id)">ON/OFF</button>
      </div>
      <div style="padding: 20px;" class="col-6 col-sm-6">
        <h2 style="padding-bottom: 50px;" class="text-center">Socket</h2>
        <button id="90" class="get_id btn btn-lg btn-block btn-primary" onclick="sendRequest(this.id)">ON/OFF</button>
      </div>
    </div>
  </div>
  <script src="../bootstrap-4.3.1/dist/js/bootstrap.min.js"></script>
</body>

</html>

checkConnection.js

JavaScript
function checkConnection(){
  // var x = document.cookie
  // if(!x){
  //   var name = prompt("Enter your name.")
  //   if(name == null ||  name == "" || name.trim().length == 0){
  //     document.getElementById("demo").innerHTML = "ERROR!! Reload the page.";
  //     return;
  //   }
  //   else{
  //     document.cookie = "name="+name;
  //     var xhttp = new XMLHttpRequest();
  //     xhttp.onreadystatechange = function(){
  //       if (this.readyState == 4 && this.status == 200){
  //         document.getElementById("demo").innerHTML = xhttp.responseText;
  //       }
  //     };
  //     xhttp.open("GET","http://127.0.0.1/IoT/server/checkConnection.php",true);
  //     xhttp.send();
  //   }
  // }
  window.location.href = "/IoT/client/home.html";

}

Credits

prabinrajupreti

prabinrajupreti

0 projects • 3 followers

Comments