Project showcase

IoT Home Security Model © CERN-OHL

A model of home security system that utilized sensors and internet to monitor the security status in real-time.

  • 34,618 views
  • 32 comments
  • 101 respects

Components and supplies

Necessary tools and machines

Apps and online services

About this project

*This project is featured in DFRobot's blog. Please refer their blog here.
*This project is nominated in Postscapes IoT Awards under category Best IoT DIY Project.

IoT Home Security Model can be remotely accessed by using any smart device and PC to monitor the security status within the house through the data collected from sensors through the Internet.

Promo Video

Promo Video for IoT Home Security Model

When security mode is turned on, any recognized harmful activities that occurred within the house will be detected through installed sensors and automatically forward the alert message to the homeowner through the internet. The data from sensors will constantly be stored in the cloud storage and interact with the custom web-based application that enables it to display the data in a website, and this allows the homeowner to have an advantage to monitor any potential harmful activity that might occur within the house in real-time. Another additional feature of security in this project is Access Control Technology, this system uses the (NFC) "Near Field Communication" approach to provide access to the recognized individuals (guests or family members) with the rights to enter the house.

Full Demonstration Video

Full Demonstration for IoT Home Security Model 

Origin

This project originally titled "Android WiFi and Web Based Application for Home Security System" and is my final year project submission during my last year of engineering in University. At that time, this project is still full of bugs and not as real-time as it should be ( data-latency could more than 2 seconds! ).

Now I took some of my free time to refurbish this project and make it much closer to real-time, and the result is quite satisfying.

Structure for this project

The structure of this model is build according to the floor plan layout as shown in schematics section. The materials that used are plywood with size 64.5cm (L) x 61.5cm (W) x 0.8cm (H) as the ground, craft plywood sheets for building the walls and main electronic components consist of 6 sensors, 1 NFC Reader and 2 microcontrollers, other minor components can refer to my components list.

Thus, the finishing product is almost 85% covered by plywood materials. Similar as building the real house with concrete, the concept of building this house is entirely depend on the strong adhesive class of reactive prepolymers and polymers that known as polyepoxides or epoxy.

System Design for this Model

The design of this system is very straight-forward, which works in a two-way flow. First flow started from the data provided by the sensors through mircocontroller and to the cloud through the internet and retrieved by any smart devices. Second flow is the response flow from user to the microcontroller installed at home through internet connection and to the responding mechanisms ( LED on/off, servo-motor, water pump, so on... ) to react. Just like the IoT layer model, I designed my own a simple layer of hierarchy for this home model.

Custom Real-Time Monitoring IoT Web-Service

The IoT web-service is custom made by myself. The features of this web-service includes real-time capability to fetch and monitoring sensors data, dashboard for home status, system warning message, storage for sensors data, full data logging and safety benchmark configuration. I'm not fully open-source the code yet, but will do it in the coming future, mark my words.  (At the time of this writing, there's still a lot of flaw about the web-service I wrote). But disappoint not, because I do find out there are some of other IoT web-services out there like Samsung's SAMI and Freeboard.io (probably more out there, but currently, I only knew these). I would like to share more details with picture about the service I wrote:

  • Picture 1: Connected Dashboard with Home Model
  • Picture 2: Safety Benchmark Configuration
  • Picture 3: Data Logging Graph
  • Picture 4: Example of 10 minutes Data Graph
  • Picture 5: Example of Full Data Logging
  • Picture 6: Example of System Warning Message
  • Picture 7: Example of Security is turned OFF using NFC
  • Picture 8: Example of Current Spike Condition
  • Picture 9: Vibration Sensor in Real-Time
  • Picture 10: Water Sensor in Real-Time
  • Picture 11: Gas Sensor in Real-Time
  • Picture 12: Temperature Sensor in Real-Time
  • Picture 13: Humidity Sensor in Real-Time
  • Picture 14: NFC Reader Data in Real-Time

*For higher resolution of these pictures, you can view it in my Dropbox, here.

Building Process:

a - Planning and Designing the House Plan

Before the house plan is being drawn, the original draft of the house plan is based on the arrangement of the sensors and furniture that being setup at the first place. The initiative involved the measurement and scaling of the arrangement for the furniture being recorded and taken account for the next proceeding step for designing the house plan. The actual presentation of the arrangement for the furniture is shown in picture below. On the left side of the figure is the breadboard with the configuration of the microcontroller and the power distribution.

b - Preparing the Construction Materials

The materials involved here is by meant of custom preparation for the house model. The materials preparation involved of plywood doors crafting, windows crafting and framework of the walls. The tasks of these preparation are shown below.

Another preparation is the circuit board for the system. I have made my own circuit board using positive acting presensitized printed circuit board. The method is very straight-forward and you can follow the full tutorial here. My printed circuit board can be seen below.

c - Prepare the Site and Foundation

This phase, the term "site" here means for the field or ground that lay before the foundation. The ground that refer here is made from the plywood with dimensions of 64.5cm (L) x 61.5cm (W) x 0.8cm (H).

While for the foundation of the house is built from the combination of 4 pieces of craft plywood sheets that having the area of 52cm (L) x 40cm (W). With this foundation where the wall framework will be built upon in the next coming phase. The preparation of the site and foundation is shown in picture below.

d - Complete the Rough Framing

This phase is very essential for the overall structure of the house because it deals with the collectively known shell or skeleton of the house which is the floor systems and walls systems. For both of these systems will be completed in this phase. Similar as the concept of building a real house, the floors and walls are cemented properly to hold firmly between the properties and protect against external force exerted on it. In this project house model, the floors and walls are finished using a strong adhesive solution known as epoxy. The finished floor systems and walls system is shown in picture below.

e - Wiring Process and Connectivity Check

In this phase, all the sensors and NFC module are being installed in the planned position. Then, the wiring process able to be proceed. In the meantime, during the wiring process, the connectivity of the circuit is tested from time to time to prevent any wiring misplaced to improper connection.

During the wiring process, there are total number up to 38 pin points that required to be completed in this task. For all the connection cables are properly categorized with accordance to the walls system which contains 4 segments that known as wall 1-cables, wall 2-cables, wall 3-cables and wall 4-cables ( all total of four main walls ). Lastly, these cables are framed to the walls within the house with strong adhesive epoxy. The examples of wiring works are shown below.

f - Complete the Internal Wall Framework

Only after all the previous phases completed, the internal wall of the framework is able to be built. Internal wall of this house is based on the house plan designed in step(a) and the completed work is shown below.

g - Move in all the Furniture!

Finally, the wall framework is completed, then the furniture can be brought in. To make it stable and unmovable, I used strong adhesive solution, eproxy to stick those furnitures on top of the foundation.

Project works with AWS IoT

I've decided to use this project to works using AWS IoT. Instead of using "HTTP" in as the original protocol, I've modified the data communication protocol using MQTT with secure connection from AWS IoT. And the result working very well, let me show the video demonstration below:

Video Demonstration with AWS IoT

The great about AWS IoT model is its emphasis on security in the cloud and cover strong authentication, for each of IoT device to be connected require credentials (X.509 certificate and AWS credential) to access the message broker. TLS is used to encrypts the connection between the device and the broker and this create an end-to-end secure communication.

[UPDATED]: Source code is available in my GitHub Repo, here

Although it is great about using this communication protocol compared to "HTTP", but there is a drawback when using this approach in this project. My original source code for Arduino Yun seems not working well with Yun-Sdk from AWS IoT, the "HTTP" LED controlling becomes obsolete. I think I will open this issue soon and takes some time to solve this issue. Overall, all sensors data working fine.

But overall, the data message works pretty well, and compared to my original "HTTP" approach, I will definitely go for "MQTT" with AWS IoT. Not only because of security, "MQTT" provide benefits such as low power usage, minimised data packets, and efficient distribution of information.

Important remarks in the source code:

/*
       Example of Publishing a Topic in AWS IoT Home Security Model
               (Code can be found in IoTHome-Yun.ino)
*/
   char userid[] = "your-user-id-here";     // line 57
   setTopic("IoTHome/nfc/");                // line 377
   aws_iot.data(arrayTopic, value0);        // line 378
   void setTopic(char* topic){              // line 383
     *arrayTopic = 0;                       // line 384
     strcat(arrayTopic, topic);             // line 385
     strcat(arrayTopic, userid);            // line 386
   }                                        // line 387
/*
       Example of Output Topic (Code can be found in iot_config.cpp)
*/
   Serial.print(topic);    // line 106
                           // will output "IoTHome/nfc/your-user-id-here"
                           // userid is used for authentication in Web App

The coding for this project is open-source, please refer to the Code Section for my Github repo with name "AWS-IoT-Home-Security-Model-HW".

Future Improvement

Home Security System is one of the significant parts for the building blocks for a smart home. Thus, my consideration is to include as many sensors as possible and make good use of the data collected are the keys to making the home more “smarter”, in my opinion, collectively will linked to the improvement of security for a house.

Problems | Questions | Comments | Suggestion

Probably, there is some technical problem in this project that I'm not aware of, you can leave a comment or private message me, your feedback is highly valued!

Any questions regarding this project also can contact me. 

All sorts of comments and suggestions are welcome.

Schematics

c. PCB Picture
Printed Circuit Board for IoT Home Security Model
Pcb final
Schematics Diagram
Schematics diagram designed for IoT Home Security Model.
Fyp schematic diagram rev2
Floor Plan
Floor plan designed for IoT Home Security Model.
Fyp homesecuritysystem floor plan design
Floor Plan
This is the floor plan designed for IoT Home Security Model.
Fyp homesecuritysystem floor plan design
PCB Picture
Printed Circuit Board for IoT Home Security Model.
Pcb final

Code

IoTHome-YunArduino
Arduino Yun Source Code for IoT Home Security Model.
/*
  THIS SOURCE CODE ORIGINALLY INTENDED FOR USE IN UCSI UNIVERSITY ENGINEERING FINAL YEAR PURPOSES ONLY,
  NOW IS FULLY OPEN-SOURCE UNDER MIT LICENSE

  The MIT License (MIT)

  Copyright (c) 2015 AaronKow
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*/

/*External library for temp + humid sensor (DHT22)*/
#include <DHT.h>

/*External library for Cloud Data*/
#include <Process.h>

/*External library enables communication between Arduino and OpenWrt-Yun*/
#include <Bridge.h>

/*External library for initiate the YunServer*/
#include <YunServer.h>

/*External library for managing the connection*/
#include <YunClient.h>

YunServer server; //enabling the the Yun to listen for connected clients

/*Current Sensor Configuration*/
const int numReadings = 5;
float readings[numReadings];  
int index = 0;                 
float total = 0;             
float average = 0;
float currentValue = 0;
float initVal = 0;

/*Ultrasonic Sensor Configuration*/
const int trigPin = 2;
const int echoPin = 3;
long duration, cm;

/*Gas Sensor Configuration*/
int gasValue;

/*TempHumid Sensor Configuration*/
const int tempPin = 5;
float t,h;                         //variables for temperature sensor
DHT dht(tempPin);                  //define temperature sensor configuration

/*Cloud Data Configuration*/
String value0, value1, value2, value3, value4, value5, value6, value7;  // For sensors values
String led1, led2, led3, led4;  // For LED values
String ipAddress = "192.168.0.105:3000";    // set your ip address here
String userid = "your-user-id-here";        // set your user id here

void setup() {
  /*Http Client Setup*/
  pinMode(8, OUTPUT);              // Living Room Lights
  pinMode(9, OUTPUT);              // Bedroom Light
  pinMode(10, OUTPUT);             // Bathroom Light
  pinMode(11, OUTPUT);             // Kitchen Light
  
  /*Current Sensor Setup*/
  pinMode(0, INPUT);  
  pinMode(13,OUTPUT);  // for transmit data to Mega
  for (int thisReading = 0; thisReading < numReadings; thisReading++){
    readings[thisReading] = 0;       
  }
  
  /*Ultrasonic Sensor Setup*/
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  
  /*Vibration Sensor Setup*/
  pinMode(A2, INPUT);
  pinMode(A3, OUTPUT);
  
  /*Water Sensor Setup*/
  pinMode(6, INPUT);
  
  /*Buzzer Pin Setup*/
  pinMode(7, OUTPUT);
  
  /*Initiate Setup*/
  Serial.begin(115200); //Set serial baud rate to 115200 bps
  Bridge.begin();  // Initialize the Bridge communication
  server.begin();  // enabling Yun to listen for connected clients
  server.noListenOnLocalhost();    // tells the server to begin listening for incoming connections  
}

void loop() {
  /*http action*/
  YunClient client = server.accept();
  if (client.connected()) {
    Serial.println("CLIENT CONNECTED!");
    process(client); // Process request
    client.stop(); // Close connection and free resources
  }
  
  clearCloudData();
  systemStatus();
  currentSensor();
  ultrasonicSensor();
  gasSensor();
  vibrationSensor();
  TempHumidSensor();
  waterSensor();
  cloudData();
  //delay(500);
}

void process(YunClient client) {
  String command = client.readStringUntil('/'); // read the command
  if (command == "digital") { // verify if command for digital
    digitalCommand(client);
  }
}

void digitalCommand(YunClient client) {
  int pin, value;
  pin = client.parseInt(); // Read pin number

  // If the next character is a '/' it means an URL preceived
  if (client.read() == '/') {
    value = client.parseInt(); // taking value from client
    digitalWrite(pin, value);  // proceed to changes on the selected pin
  } 
  else {
    value = digitalRead(pin); // read value if no changes made
  }

  // Send feedback to client
  client.print(F("Pin D"));
  client.print(pin);
  client.print(F(" set to "));
  client.println(value);
  Serial.println(value);

  // Update datastore key with the current pin value
  String key = "D";
  key += pin;
  Bridge.put(key, String(value));
}

void clearCloudData(void){
  value0 = value1 = value2 = value3 = value4 = value5 = value6 = value7="";
}

void systemStatus(void){
  if(digitalRead(12) == 1){
    value0 += 1;
  }
  else{
    value0 += 0;
  }
}

void currentSensor(){
  total= total - readings[index];
      if(digitalRead(12) == 1){
        readings[index] = analogRead(0);
        readings[index] = (readings[index]-512)*5/1024/0.04+2.85;   // calibrate your own current sensor here
        total= total + readings[index];       
        index = index + 1;                    
        if (index >= numReadings)              
          index = 0;                           
        average = total/numReadings;
        currentValue = average;
        if (currentValue<0){
          currentValue = 0.51;    // this to ensure current stay at 0.51A if current drop below 0A
        }
        value1 += currentValue;
      }
      else{
        currentValue = 0;
        value1 += 0;
      }
      
      Serial.println(currentValue);
      
      if (currentValue >1){ //TO BE ADJUST
        digitalWrite(13, HIGH);
        buzzer(true);
        cloudData();
      }
      else{
        digitalWrite(13, LOW);
        buzzer(false);
      }
      delay(20);
}

void ultrasonicSensor(){  //require to adjust
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  cm = (duration / 29 / 2)+3;  // to centimetres

  if (cm < 20){ //eliminate data fluctuation
    buzzer(true);
    delay(500);
  }
  else{
    buzzer(false);
  }
  
  Serial.print(cm);
  Serial.println(" cm");
  value2 += cm;
  delay(20);
}

void gasSensor(){
  gasValue=(analogRead(5) * 0.01); //Read Gas value from analog 0
  Serial.println(gasValue, DEC);  //Print the value to serial port
  value3 += (gasValue);
  if(gasValue<6){
    if(gasValue == 0){
      buzzer(false);
    }
    else{
      buzzer(true);
    }
  }
  else{
    buzzer(false);
  }
  delay(20);
}

void vibrationSensor(){
  if(digitalRead(12) == 1){
    digitalWrite(A3, !digitalRead(A2));
    if (digitalRead(A2) != digitalRead(A3)){
      buzzer(true);
      delay(500);
      Serial.println("Vibrated!"); //1
      value4 += 1;
    }
    else{
      buzzer(false);
      Serial.println("No Vibration..."); //0
      value4 += 0;
    }
  }
  else{
    //Serial.println("No Signal!");
    buzzer(false);
    value4 += 0;
  }
}

void TempHumidSensor(){
  // Wait a few seconds between measurements.
  delay(20); //2000 = 2 seconds

  // Reading temperature or humidity takes about 250 milliseconds!
  // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  h = dht.readHumidity();
  // Read temperature as Celsius
  t = dht.readTemperature();
  Serial.print("Humidity: "); 
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: "); 
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print("\n");
  value5 += t;
  value6 += h;
}

void waterSensor(){
  if (digitalRead(12) == HIGH){
    if (digitalRead(6) == LOW){
      buzzer(true);
      Serial.println("Water Status Warning!"); //1
      value7 += 0;
    }
    else{
      buzzer(false);
      Serial.println("Water Status OK"); //0
      value7 += 1;
    }
    delay(20);
  }
  else{
    //Serial.println("No Signal");
    value7 += 1;
  }
}

void buzzer(boolean sound){
  if(digitalRead(12) == 1){ //1 means security system is online
    if(sound){
      digitalWrite(7, HIGH);
      delay(100);
    }
    else{
      digitalWrite(7, LOW);
    }
  }
  else{  //disable any buzzer if system offline
    digitalWrite(7, LOW);
  }
}

void cloudData(void){
  if(value0 == "0")
  {
    value0 = "0";
    value1 = value2 = value3 = value4 = value5 = value6 = value7="";
  }

  led1 =  digitalRead(8);
  led2 =  digitalRead(9);
  led3 =  digitalRead(10);
  led4 =  digitalRead(11);
  
  Process p;
  p.runShellCommand("curl \"http://" + ipAddress + "/ledstatus?userid=" + userid + "&led1state=" + led1 + "&led2state=" + led2 + "&led3state=" + led3 + "&led4state=" + led4 + "\" -k");
  p.runShellCommand("curl \"http://" + ipAddress + "/sensordata?userid=" + userid + "&ultrasonic=" + value2 + "&current=" + value1 + "&vibration=" + value4 + "&water=" + value7 + "&gas=" + value3 + "&temp=" + value5 + "&humid=" + value6 + "&nfc=" + value0 +"\" -k");
  while(p.running()); 
  //delay(100);
}
IoTHome-MegaArduino
Arduino Mega 2560 Source Code for IoT Home Security Model.
/*
  THIS SOURCE CODE ORIGINALLY INTENDED FOR USE IN UCSI UNIVERSITY ENGINEERING FINAL YEAR PURPOSES ONLY,
  NOW IS FULLY OPEN-SOURCE UNDER MIT LICENSE

  The MIT License (MIT)

  Copyright (c) 2015 AaronKow
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files (the "Software"), to deal
  in the Software without restriction, including without limitation the rights
  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  copies of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:
  
  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.
  
  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  THE SOFTWARE.
*/


//pin 3 to control relay power for Ultrasonic and gas sensor
//pin 4 to power vibration sensor
//pin 5 to power Temp + Humid sensor
//pin 6 to power Water sensor
//pin 7 to show NFC-System Status Red Light
//pin 8 to show NFC-System Status Green Light
//pin 12 to notify Yun about System Status
//pin 13 to receive current status from Yun

/* NFC Configuration source code from dfRobot Wiki, link: http://goo.gl/qfvi4e */
const unsigned char wake[16]={
  0x55, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};//wake up NFC module
const unsigned char firmware[9]={
  0x00, 0x00, 0xFF, 0x02, 0xFE, 0xD4, 0x02, 0x2A, 0x00};
const unsigned char tag[11]={
  0x00, 0x00, 0xFF, 0x04, 0xFC, 0xD4, 0x4A, 0x01, 0x00, 0xE1, 0x00};//detecting tag command
const unsigned char std_ACK[25] = {
  0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x0C,
  0xF4, 0xD5, 0x4B, 0x01, 0x01, 0x00, 0x04, 0x08, 0x04, 0x00, 0x00, 0x00, 0x00, 0x4b, 0x00};
unsigned char old_id[5];
const unsigned char samConfig[10]={
  0x00, 0x00, 0xFF, 0x03, 0xFD, 0xD4, 0x14, 0x01, 0x17, 0x00};
  
const unsigned char myCard[25]={
  /* Set your NFC here */
  // Example of my phone NFC below:
  // My phone NFC:   0 0 FF 0 FF 0 0 0 FF 11 EF D5 4B 1 1 0 4 25 91 5 4 3 2 1 79 
  0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x11,
  0xEF, 0xD5, 0x4B, 0x01, 0x01, 0x00, 0x04, 0x25, 0x91, 0x05,
  0x04, 0x03, 0x02, 0x01, 0x79};
 
unsigned char receive_ACK[25];//Command receiving buffer
//int inByte = 0;               //incoming serial byte buffer
 
/*External include for NFC*/
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#define print1Byte(args) Serial3.write(args)
#define print1lnByte(args)  Serial3.write(args),Serial3.println()
#else
#include "WProgram.h"
#define print1Byte(args) Serial3.print(args,BYTE)
#define print1lnByte(args)  Serial3.println(args,BYTE)
#endif

void setup() {
  /*NFC Setup*/
  Serial3.begin(115200);    //open Serial3 with device
  //while (!Serial);
  wake_card();
  SAMConfig();
  delay(100);
  read_ACK(15);
  delay(100);
  display(15);
  Serial.println("Read Firmware");
  firmware_version();
  delay(100);
  read_ACK(19);
  delay(100);
  display(19);
  
  /*Data Transmission to Yun Setup*/
  pinMode(12, OUTPUT);  //Tell Yun where system Logged in or out
  digitalWrite(12, HIGH);
  
  /*System Status Setup*/
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  digitalWrite(7, LOW);
  digitalWrite(8, HIGH);
  
  /*General Setup*/
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(13, INPUT);
  digitalWrite(3, LOW);  //to control relay
  digitalWrite(4, HIGH);
  digitalWrite(5, HIGH);
  digitalWrite(6, HIGH);
  Serial.begin(115200);   // open serial with PC
}

void loop() {
  //Serial.println(digitalRead(13));
  checkStatus();
  nfc();
}

void nfc(){
  send_tag();
  delay(100); 
  read_ACK(25);
  delay(100);
  Serial.println("Display Tag:");
  display (25);
  checkID();
  delay(200);
  //delay(2500);
  //copy_id ();
}

void checkID(void){
  int j;
  for (j=0; j<25; j++){
    if (receive_ACK[j] == myCard[j]){
      //proceed for validation
    }
    
    else{
      Serial.println("Scanning for Card...");
      break;
    }
  }
  if (j==25){
    Serial.println("Card Recognized!");
    digitalWrite(12, !digitalRead(12));
    digitalWrite(7, !digitalRead(7));
    digitalWrite(8, !digitalRead(8));
    if(digitalRead(12) == HIGH){
      Serial.println("System Online");  //Security system offline
    }
    else{
      Serial.println("System Offline");  
    }
  }
}
 
/*void copy_id (void) 
{//save old id
  int ai, oi;
  for (oi=0, ai=19; oi<5; oi++,ai++) {
    old_id[oi] = receive_ACK[ai];
  }
}*/
 
  
char cmp_id (void) 
{//return true if find id is old
  int ai, oi;
  for (oi=0,ai=19; oi<5; oi++,ai++) {
    if (old_id[oi] != receive_ACK[ai])
      return 0;
  }
  return 1;
}
 
 
int test_ACK (void) 
{// return true if receive_ACK accord with std_ACK
  int i;
  for (i=0; i<19; i++) {
    if (receive_ACK[i] != std_ACK[i])
      return 0;
  }
  return 1;
}
 
 
void send_id (void) 
{//send id to PC
  int i;
  Serial.print ("ID: ");
  for (i=19; i<= 23; i++) {
    Serial.print (receive_ACK[i], HEX);
    Serial.print (" ");
  }
  Serial.println ();
}
 
 
void UART1_Send_Byte(unsigned char command_data)
{//send byte to device
  print1Byte(command_data);
#if defined(ARDUINO) && ARDUINO >= 100
  Serial3.flush();// complete the transmission of outgoing serial data 
#endif
} 
 
 
void UART_Send_Byte(unsigned char command_data)
{//send byte to PC
  Serial.print(command_data,HEX);
  Serial.print(" ");
} 
 
 
void read_ACK(unsigned char temp)
{//read ACK into reveive_ACK[]
  unsigned char i;
  for(i=0;i<temp;i++) {
    receive_ACK[i]= Serial3.read();
  }
}
 
 
void wake_card(void)
{//send wake[] to device
  unsigned char i;
  for(i=0;i<16;i++){ //send command
    UART1_Send_Byte(wake[i]);
    //Serial.print(wake[i], HEX);
  }
}
 
 
void firmware_version(void)
{//send fireware[] to device
  unsigned char i;
  for(i=0;i<9;i++) //send command
    UART1_Send_Byte(firmware[i]);
}
 
 
void send_tag(void)
{//send tag[] to device
  unsigned char i;
  for(i=0;i<11;i++) //send command
    UART1_Send_Byte(tag[i]);
}
 
 
void display(unsigned char tem)
{//send receive_ACK[] to PC
  unsigned char i;
  for(i=0;i<tem;i++) //send command
    UART_Send_Byte(receive_ACK[i]);
  Serial.println();
}

void SAMConfig(void)
{
  unsigned char i;
  for(i=0;i<10;i++){ //send command
    UART1_Send_Byte(samConfig[i]);
  }
}

void checkStatus(void){
  if(digitalRead(12) == 0){ //system offline
    digitalWrite(3, HIGH);
    digitalWrite(4, LOW);
    digitalWrite(5, LOW);
    digitalWrite(6, LOW);
  }
  else{  //system online
    if(digitalRead(13) == 1){ //check current status
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
      digitalWrite(5, LOW);
      digitalWrite(6, LOW);
    }
    
    else{ //system back online
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
      digitalWrite(5, HIGH);
      digitalWrite(6, HIGH);
    }
  }
}
Modified DHT.cppC/C++
Modified DHT.cpp for IoT Home Security Model
/* 
  DHT library

  MIT license
  written by Adafruit Industries

  Modified by Aaron Kow for IoT Home Security Model
*/

#include "DHT.h"

DHT::DHT(uint8_t pin, uint8_t count) {
  _pin = pin;
  _count = count;
  firstreading = true;
}

void DHT::begin(void) {
  // set up the pins!
  pinMode(_pin, INPUT);
  digitalWrite(_pin, HIGH);
  _lastreadtime = 0;
}

//boolean S == Scale.  True == Farenheit; False == Celcius
float DHT::readTemperature(void) {
  float f;

  if (read()) {
      f = data[2] & 0x7F;
      f *= 256;
      f += data[3];		//>>>>>>>> improvement required<<<<<<<<
      f /= 10;
      if (data[2] & 0x80){ //negative-checker, if the and equate to 1 is true
	     f *= -1;
      }
      return f;
  }

  else{
  	return NAN;
  }
}

float DHT::readHumidity(void) {
  float f;
  if (read()) {
      f = data[0];
      f *= 256;
      f += data[1];	//>>>>>>>> improvement required<<<<<<<<
      f /= 10;
      return f;
  }

  else{
    return NAN;
  }
}

boolean DHT::read(void) {
  uint8_t laststate = HIGH;
  uint8_t counter = 0;
  uint8_t j = 0, i;
  unsigned long currenttime;

  // Check if sensor was read less than two seconds ago and return early
  // to use last reading.
  currenttime = millis();
  if (currenttime < _lastreadtime) {	//reset the last read time
    _lastreadtime = 0;
  }

  if (!firstreading && ((currenttime - _lastreadtime) < 2000)) {
    return true; // return last correct measurement
    //delay(2000 - (currenttime - _lastreadtime));
  }

  firstreading = false;
  /*
    Serial.print("Currtime: "); Serial.print(currenttime);
    Serial.print(" Lasttime: "); Serial.print(_lastreadtime);
  */
  _lastreadtime = millis();

  data[0] = data[1] = data[2] = data[3] = data[4] = 0;	//clear data
  
  // pull the pin high and wait 250 milliseconds
  digitalWrite(_pin, HIGH);
  //original delay(250);

  // now pull it low for ~20 milliseconds
  pinMode(_pin, OUTPUT);
  digitalWrite(_pin, LOW);
  delay(20);
  noInterrupts();			//disable interrupt for time-sensitive code
  digitalWrite(_pin, HIGH);
  delayMicroseconds(40);
  pinMode(_pin, INPUT);

  // read in timings
  for ( i=0; i< MAXTIMINGS; i++) {	//MAXTIMINGS = 85
    counter = 0;
    
  /*calibrated:response to the sensor,
    break once pin turns high.*/	
    while (digitalRead(_pin) == laststate) {	//intially laststate = high
      counter++;		
      delayMicroseconds(1);
      if (counter == 255) {	//255 is the maximum timeout
        break;
      }
    }
    laststate = digitalRead(_pin);

    if (counter == 255) break;	//if timeout, break directly

    /* 
	Condition 1: ignore first 3 transitions
	Condition 2: accept only figure divide by 2
    */
    if ((i >= 4) && (i%2 == 0)) {
      // shove each bit into the storage bytes
      data[j/8] <<= 1;	//divide by eight to ensure whole number, 0-4
      if (counter > _count) //_count here represent 60us
        data[j/8] |= 1;
      j++;
    }
  }

  interrupts();

  // check we read 40 bits and that the checksum matches
  if ((j >= 40) && 
      (data[4] == ((data[0] + data[1] + data[2] + data[3]) & 0xFF)) ) {
    return true;
  }
  else{
    return false;    
  }
}
Modified DHT.hC/C++
Modified DHT.h for IoT Home Security Model
/* 
  DHT library

  MIT license
  written by Adafruit Industries

  Modified by Aaron Kow for IoT Home Security Model
*/

#ifndef DHT_H
#define DHT_H
#if ARDUINO >= 100

#include "Arduino.h"
#else
 #include "WProgram.h"
#endif

#define MAXTIMINGS 85

class DHT {
 private:
  uint8_t data[6];
  uint8_t _pin, _count;
  unsigned long _lastreadtime;
  boolean firstreading;

 public:
  DHT(uint8_t pin, uint8_t count=6);
  void begin(void);
  float readTemperature(void);
  float readHumidity(void);
  boolean read(void);
};
#endif
IoT-Home-Security-Model-HW
Source code repository for IoT Home Security Model Harewares
AWS-IoT-Home-Security-Model-HW
Source code repository for AWS IoT Home Security Model Hardwares
AWS-IoT-Home-Security-Model-SW [Not Longer Maintain]
Source codes for IoT Home Security Model Dashboard using AWS IoT

Comments

Similar projects you might like

Pac-Man LED Pixel Panel Costume

Project tutorial by Ben Muller

  • 5,697 views
  • 4 comments
  • 94 respects

LoRa Gateway for DeviceHive

Project tutorial by DeviceHive IoT team

  • 1,494 views
  • 2 comments
  • 19 respects

Really Smart Box

Project tutorial by Stephen Harrison

  • 4,070 views
  • 2 comments
  • 15 respects

Raspberry Pi and Arduino Laptop

Project tutorial by Dante Roumega

  • 18,322 views
  • 6 comments
  • 45 respects

IoT Bird Feeder with Sigfox and Tweeter

Project showcase by Gaël Porté

  • 646 views
  • 0 comments
  • 9 respects
Add projectSign up / Login