What do you know about Zero Ohm's consulting services?

IoT: Door Sensor

Posted by Momen 14/09/2017 0 Comment(s)

Welcome to Zeroohm Arduino Training series. In this series of Arduino Training, Zeroohm will focus its efforts on helping the community learn more about Arduino fundamentals and basics starting with basic control of LED's, motors, sensors and utilizing of wirless communication. We hope that you find this useful, Please, leave a comment for any questions or comments or reviews!

We provide all our trainings for groups from schools, universities, public sector and private sector in Abu Dhabi, Dubai, Sharjah, Fujirah, RAK or anywhere in UAE. Please,click here to contact us directly for any training inquires.

We are also an authorized Arduino distributor for the UAE, Oman and Qatar. We can provide you with any product of your choice. Please, contact us for inquires.

Our internet of things (IoT) training series:

1. Introduction to IoT using Arduino

2. IoT: Humidity and Temperature Sensor

3. IoT: Door Sensor

In this tutorial, I will try to explain how to implement a simple door sensor using Arduino MKR1000 board and IOT (Internet of Things) technology. Below is a list of all hardware components used in this tutorial.

Hardware Components:

  • Arduino MKR1000 board
  • LIPO Battery 1000mAh
  • Micro Limit Switch
  • USB cable
  • And of course, pins, wires and a breadboard even though it’s not compulsory.

The MKR1000 board can be replaced by using a ESP8266 Wifi module and Arduino UNO board. MKR1000 is used here since it reduces the wiring. The battery too can be replaced by any other power source. The Micro Limit Switch basically acts as a proximity sensor and can be replaced by magnetic contact switches which gives a similar function.

Hardware Design:

The hardware connection is pretty simple as shown below:

door-sensor-iot-circuit

 

 

 

 

 

NOTE: In the above circuit, I have used a pushbutton to model the limit switch. The USB cable will be used initially during the programming phase and then replaced by the battery.

Now we are done with the easy part, now onto the most fun and difficult part which is the software!

Software Design:

So basically, we will be using ‘Artik Cloud’, which is an open source, secure IoT Cloud platform owned by Samsung. The program running on the MKR1000 will check the status of the switch every 15 minutes or whatever time you set it. Below is the algorithm of the code which will give you a general idea of how the system will work.

  1. Every 15 minutes or so the MKR1000 will connect to the Wifi.
  2. Turn on the board LED.
  3. Send an update to the cloud platform with changes sensed by the limit switch, for example it will sense the closing and opening of doors.
  4. Disconnect from Wifi.
  5. Turn off the board LED.
  6. Whole process repeats again.

NOTE: You can also put counters in the program to check the success and failure rates of the MKR1000 board trying to send data over the cloud.

Now to make our simple door sensor into an IoT device! To do that, follow the below steps:

Step 1- Go to ‘https://developer.artik.cloud/’, and sign up. If you don’t have a Samsung account, you can sign up with your Google account.

Step 2- In the ‘Device Types’, select ‘+ New Device Type’.

 artik-homepage

Step 3- Give your device a name and a unique name as shown in the picture below. After this, click ‘Create Device Type’.

creating-a-new-device-in-artik

Step 4- Click ‘+ New Manifest’ for your device.

creating-a-new-manifest-in-artik

Step 5- Add 3 fields names, ‘open’, ‘closed’ and ‘failed’. All their data types should be integer. Leave rest of the boxes empty along with the ‘Device Actions’ tab. Save your manifest. End result is shown below.

creating-fields-in-artik

Step 6- After activating the manifest, go to ‘https://my.artik.cloud/new_device’. I’m assuming you are already signed in. Search for your device in the search bar.

artik-cloud-seach-device

Step 7- Activate it. Now click on the device to show its info. Take note of the Device ID and Device token.

device-information-artik-cloud

 

 

 

 

 

 

 

 

 

 

 

 

We are done setting up the device in the IoT platform. Now to configure your MKR1000 board!

Step 8- Open Arduino IDE software, in the ‘Tools’ menu, select ‘Boards Manager’. Type MKR100 in the search box and select ‘Arduino SAMD Boards’ in the results. Install it.

mkr1000-board-installation

Step 9- Now go to ‘Sketch’, in the ‘Include library’ section, select ‘Manage libraries’. In the search bar type ‘Wifi101’ and ‘ArduinoJson’. Install both of them. Installation of Wifi101 is shown below.

installing-wifi-101-library

Now we can finally get started with the code!

Step 10- Declare libraries, variables and initializations. You know the drill!

#include <WiFi101.h>

#include <ArduinoJson.h>

//TESTED WITH GENUINO/ARDUINO MKR1000

//Web REST API params

char server[] = "api.artik.cloud";

int port = 443; //(port 443 is default for HTTPS)

String AuthorizationData = "Authorization: Bearer <DEVICE TOKEN>"; // CHANGE HERE YOU FOUND THE VALUE ON ARTIC.CLOUD/mydevices

float insTemp;

char buf[200];

#define LED 6

#define DOORSWITCH 2

#define OPENSTATE 1

#define CLOSEDSTATE 0

int ledState = 0;

int openCount = 0;  //the door changed to open in the last 15 minutes

int closedCount = 0; //the door changed to closed

int failedSend = 0; //number of failed send of data.. it counts how many failed times it tried to send the data.

WiFiSSLClient client;

char ssid[] = "<YOURWIFISSID>";      // CHANGE HERE

char pass[] = "<YOURWIFIPASSWORD>"; // CHANGE HERE

int status = WL_IDLE_STATUS;

unsigned long lastRequest = 0L;

const unsigned long TIMEFORUPDATE = 1000L * 15L * 60L; //15 minutes

int doorState = 0;

void setup() {

Serial.begin(9600);

pinMode(LED,OUTPUT);

pinMode(DOORSWITCH,INPUT_PULLUP);

Serial.println("Starting.");

}

//onboard led off

void ledOFF() {

digitalWrite(LED,LOW);

}

//onboard led on

void ledON() {

digitalWrite(LED,LOW);

}

//loop to attempt connecting to wifi

void connectWiFi() {

int retry = 10;

while (status != WL_CONNECTED) {

Serial.print   ("Attempting to connect to WiFi ");

Serial.println (retry);

status = WiFi.begin(ssid,pass);

delay(30);

retry--;

if(retry < 0) {

Serial.println("Failed to connect..");

break;

}

}

if( status != WL_CONNECTED && retry >= 0 ) {

Serial.println("connected to WiFi ");

}

}

// helper function..

void disconnectWiFi() {

WiFi.disconnect();

}

//http post request to artic cloud

void newArticRequest() {

client.connect(server, port);

if (!client.connected()) {

Serial.println("Artic Request Error.");

failedSend++;

} else {

Serial.println("Data open "+String(openCount) +" closed "+ String(closedCount));

client.println("POST /v1.1/messages HTTP/1.1");

client.println("Host: api.artik.cloud");

client.println("Accept: */*");

client.println("Content-Type: application/json");

client.println("Connection: close");

client.println(AuthorizationData);

// Automated POST data section

client.print("Content-Length: ");

client.println(makeJSON()); // loads buf, returns length

client.println();

client.println(buf);

Serial.println("Artic Request Sent.");

client.stop();

failedSend=0;

}

lastRequest = millis();

}

//this check , to control if the device should send data to artic

bool timeToSend(){

if( (millis() - lastRequest) > TIMEFORUPDATE ) {

Serial.println("TIME TO SEND OK.");

return true;

}

//Serial.println("NOT READY TO SEND." + String(millis()) +" "+ String (lastRequest) );

return false;

}

Step 11- This is the part of the code where the fun stuff happens.

void loop() {

int tmpDoorSwitch = digitalRead(DOORSWITCH); //check the switch

Serial.println("Switch status: " + String(tmpDoorSwitch));

if( tmpDoorSwitch != doorState ) { //check the door switch, if it is changed

doorState = tmpDoorSwitch;

if(doorState == OPENSTATE) //the door changed to open

openCount++;

if(doorState == CLOSEDSTATE) //the door changed to close

closedCount++;

}

if( timeToSend() ) {

delay(200);

Serial.println("TIME TO SEND.");

ledON();

Serial.println("Connecting...");

connectWiFi();

newArticRequest();

disconnectWiFi();

Serial.println("DONE...");

ledOFF();

openCount = 0;

closedCount = 0;

}

delay(1000);

}

//prepare JSON packet to send

int makeJSON() {

StaticJsonBuffer<250> jsonBuffer; // reserve spot in memory

JsonObject& root = jsonBuffer.createObject(); // create root objects

root["sdid"] = "<DEVICE_ID>"; // CHANGE HERE , YOU FOUND THE VALUE ON ARTIC.CLOUD/mydevices

root["type"] = "message";

JsonObject& dataPair = root.createNestedObject("data"); // create nested objects

dataPair["open"] = openCount;

dataPair["close"] = closedCount;

dataPair["failed"] = failedSend;

root.printTo(buf, sizeof(buf)); // JSON-print to buffer

return (root.measureLength()); // also return length

}

Step 12- After compiling and running the code on the board successfully, open and close the switch a couple of times. Wait for 15 minutes.

Step 13- Sign in into ‘Artik Cloud’ and select your device. You should see something similar to the results below:

artik-cloud-results-page

Congratulations! You have implemented an IoT device using Artik Cloud.

Signing Off Note: The project can be improved further by making a ‘WebApp’ which would send you messages to you on Gmail or Hotmail regarding the status of the door, whether its closed or open.

Since I have nothing to add anymore, I will say my Goodbyes. I hope this tutorial was useful for you and you enjoyed it!

Leave a Comment