IoT: Door Sensor – Zero Ohm Electronics

IoT: Door Sensor

Posted by Momen Odeh on

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 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 ‘’, 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 Cloud Home

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

Artik Cloud Home

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

Artik Cloud Home

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.

Artik Cloud Home

Step 6- After activating the manifest, go to ‘’. I’m assuming you are already signed in. Search for your device in the search bar.

Activate Device

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



Device Activation Page

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.

Installation of MKR1000 board

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.

WiFI library installation

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>


//Web REST API params

char server[] = "";

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


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


int status = WL_IDLE_STATUS;

unsigned long lastRequest = 0L;

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

int doorState = 0;

void setup() {






//onboard led off

void ledOFF() {



//onboard led on

void ledON() {



//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);



if(retry < 0) {

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




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

Serial.println("connected to WiFi ");



// helper function..

void disconnectWiFi() {



//http post request to artic cloud

void newArticRequest() {

client.connect(server, port);

if (!client.connected()) {

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


} else {

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

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


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

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

client.println("Connection: close");


// Automated POST data section

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

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



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




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


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



if( timeToSend() ) {


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








openCount = 0;

closedCount = 0;




//prepare JSON packet to send

int makeJSON() {

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

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


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:

Results tut

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!

Share this post

← Older Post Newer Post →

Leave a comment

Please note, comments must be approved before they are published.

Liquid error: Could not find asset snippets/bold-currency-converter.liquid