Door Status Monitor using the ESP8266

In this project you’re going to monitor the status of a door using an ESP8266. The goal of this project is to show the endless possibilities that this $4 WiFi module offers when integrates with a free platform that I’m about to show you.

Before continue reading this project, please complete the following tutorials or use them as a reference:

If you like the ESP and you want to do more projects you can read my eBook Home Automation Using ESP8266.

Let’s get started!

First, watch the video demonstration below

About IFTTT

In order to accomplish this task you have to sign up for one free service called IFTTT which stands for “If This Then That”.

IFTTT is a platform that gives you creative control over dozens of products and apps.

You can make apps work together. For example when you send a request to IFTTT, it triggers a recipe that sends you an email alert.

Creating Your IFTTT Account

Creating an account on IFTTT is free!

Go the official site: https://ifttt.com/ and click the “Sign Up” button in top of the page.

Complete the form with your personal information (see figure below) and create your account.

ifttt signup

After creating your account, follow their getting started tutorial.

Open the Applet

I’ve created an Applet that integrates perfectly in this project and you can also use it.

If you’re logged in at IFTTT and you open this URL below to use my Applet instantly:

Press the “Turn on” button:

Next, you need to grant access permissions:

Let your IFTTT account connect to your Gmail account. A new page loads when you finish connecting your Gmail.

Complete the Applet

Fill the Applet with your own information. Follow these instructions:

  1. Type “door_status” in your event name
  2. Add an email address
  3. Edit the subject and body of your email. Do not delete the Value1 in the subject
  4. Press the “Save” button

Now, go to this URL: https://ifttt.com/maker_webhooks and open the “Settings” tab.

Copy you secret key to a safe place (you’ll need them later in this project). In my example my secret key is: b6eDdHYblEv2Sy32qLwe

Test Your Applet

Let’s test if your request is working properly. Replace YOUR_API_KEY from the following URL:

https://maker.ifttt.com/trigger/door_status/with/key/YOUR_API_KEY

With your API KEY:

https://maker.ifttt.com/trigger/door_status/with/key/b6eDdHYblEv2Sy32qLwe

Open your URL with your API KEY in your browser.

ifttt triggered

You should see something similar to the preceding Figure. Then go to your email client and new email should be there!

email

Parts List

Here’s the hardware that you need to complete this project:

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Schematics (3.3V FTDI Programmer)

The schematics to upload code to your ESP8266 are very straight forward. You only need to establish a serial communication between your FTDI programmer and your ESP8266 to upload some code.

Uploading your ESP8266 code

Having the ESP8266 add-on for the Arduino IDE installed (How to Install the ESP8266 Board in Arduino IDE).

Go to Tools and select “Generic ESP8266 Module”.

Copy the sketch below to your Arduino IDE. Replace the SSID, password and the IFTTT API Key with your own credentials.

/*
 Created by Rui Santos
 
 All the resources for this project:
 https://randomnerdtutorials.com/
 
 Based on some ESP8266 code examples 
*/

#include <ESP8266WiFi.h>

const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
const char* host = "maker.ifttt.com";
const char* apiKey = "YOUR_IFTTT_API_KEY";

int pin = 2;
volatile int state = false;
volatile int flag = false;
const char* door_state = "closed";

unsigned long previousMillis = 0; 
const long interval = 3000;

void changeDoorStatus() {

    unsigned long currentMillis = millis();
 
    if(currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;   
    
        state = !state;
        if(state) {
            door_state = "opened";
        }
        else{
            door_state = "closed";
        }
        flag = true;
        Serial.println(state);
        Serial.println(door_state);
    }
    
}


void setup() {
    Serial.begin(115200);
    delay(100);
    Serial.println("Preparing the Door Status Monitor project...");
    
    pinMode(pin, OUTPUT);
    attachInterrupt(digitalPinToInterrupt(pin), changeDoorStatus, CHANGE);

    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);
    
    WiFi.begin(ssid, password);
    
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
  
    Serial.println("");
    Serial.println("WiFi connected");  
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());  
}

void loop() {

      if(flag){
          Serial.print("connecting to ");
          Serial.println(host);
          
          WiFiClient client;
          const int httpPort = 80;
          if (!client.connect(host, httpPort)) {
            Serial.println("connection failed");
            return;
          }
    
          String url = "/trigger/door_status/with/key/";
          url += apiKey;
          
          Serial.print("Requesting URL: ");
          Serial.println(url);
          client.print(String("POST ") + url + " HTTP/1.1\r\n" +
                       "Host: " + host + "\r\n" + 
                       "Content-Type: application/x-www-form-urlencoded\r\n" + 
                       "Content-Length: 13\r\n\r\n" +
                       "value1=" + door_state + "\r\n");
          flag = false;
      }  
      delay(10);
}

View raw code

After modifying my sketch upload it to your ESP8266 (If you can’t upload code to your ESP8266, read this troubleshooting guide).

Final Circuit

Now follow the schematics below to create your Door Status Monitor.

magnetic contact switch_bb

Demonstration

For prototyping/testing you can apply the magnetic reed switch to your door using Velcro.

esp8266 featured image

Now when someone opens/closes your door you get notified via email (watch the video at the beginning of this project for a live demonstration).

Wrapping Up

Do you have any questions? Leave a comment down below!

Thanks for reading. If you like this post probably you might like my next ones, so please support me by subscribing my blog.

P.S. If you got stuck during this tutorial make sure you read “ESP8266 Troubleshooting Guide


Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »

Learn how to program and build projects with the ESP32 and ESP8266 using MicroPython firmware DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our weekly newsletter!

127 thoughts on “Door Status Monitor using the ESP8266”

  1. What kind of component beside 10kΩ resistor on mini breadboard?
    Kweeelll project. I’m going to attempt this.
    Can I convert to python language?

  2. What about Energy consumption? I guess that code inside loop will drain the battery soon.
    Shouldn’t be better to use the sleep function?

    Thanks!

    • Hi Javier,
      Power consumption wasn’t a concern in this project and I’m using the ESP8266 connected to a wall power supply.
      But the sleep function might be a great enhancement to this project

      Thanks!

  3. This is great, Rui. I’ve been a fan since I first started tinkering 🙂 I was wondering if this works the same way as a bluetooth HC-05 module ? I have tried something similar but i ran it off my phone, the only problem was that had to be on 24×7. Does this module have a workaround where it turns the entire setup on and off based on PC messages ?

    • Hi Assad,
      Thank you for your continuous support!
      The HC-05 is a bluetooth module that it’s not connected to the internet. The ESP8266 is a WiFi module, so it’s actually connected to the Internet to send those emails.
      This project is also running 24×7, but you can stop and restart the project whenever you feel like.

      Rui

  4. Olá,

    great! I’m thinking to use this with a washing machine to get a notification of the end of the laundering, but I will get the info on the LED END notification for this i’m thinking use a photo-resistor, you now if I can simply change the reed switch by the photo resistor?
    Necessary to change the code?

  5. Hi can someone please clarify the following
    const char* ssid = “YOUR_SSID”;
    const char* password = “YOUR_PASSWORD”;
    I know the SSID of my wifi modem as it comes up on the PC Task bar.
    Is “YOUR_PASSWORD” the MODEM password or is it the “Network KEY”
    When connecting a friend to my home network they search for the SSID and then enter the “Network KEY”. I assume its the network KEY I need here NOT the modem password. My problem is Ive tried both and neither work. So I have another problem but I need to get the password correct. Can anybody confirm this.

    • Hi,
      The SSID is the name that you see in your computer as the network name.
      And the password is the same password you need to enter in order to your router with any device…

      How are you sure that your ESP isn’t connecting to your router?
      What do you see in your Arduino IDE serial monitor at a baud rate of 115200?

      • Hi Rui
        I found the problem I had the CPU set at 80 MHz.
        The Arduino Serial Monitor output is ..
        WiFi connected
        IP address:
        10.0.0.105
        1
        opened
        connecting to maker.ifttt.com
        Requesting URL: /trigger/door_status/with/key/c8O
        0
        closed
        connecting to maker.ifttt.com
        Requesting URL: /trigger/door_status/with/key/c8O

        Looking good now.
        Thanks

  6. Olá Rui! Tenho acompanhado seus excelentes tutoriais;
    Mas, gostaria de uma informação: Qual a diferença deste ESP8266 para o Módulo Bluetooth HC-06 ou 05?
    Obrigado

  7. This worked great with the “ESPDuino Development Board ESP13 UNO R3 With Wifi” from Banggood. This was also my first time using an IFTTT account. I really appreciate your time in posting this for all of us.

  8. pinMode(pin, OUTPUT);
    Please, is that correct ? GPIO_2 shouldn`t be and INPUT pin in order to catch the sensor status ? Thank you very much for your work.

  9. Please ignore my previous question about pinMode(pin)… I`ve just read about attachInterrupt function. It`s clear now. Sorry and thanks again !

      • got it working it was my gmail not connecting. I have to say this is amazing and thank you. I am using it as a sump pump monitor with a little float switch to email me when water level gets too high (IE the sump pump failed). I am using a NodeMcu and the arduino ide works perfectly on it. what I am trying to figure out now is can it be modified to look at a second gpio for my second sump pump. then send a email as to which pump has failed. once again thank you .
        alan

  10. Got your message today, but does not matter, never too many projects using ESP8266.
    Thanks a lot gonna try them soon.

  11. Hi thanks for the great project
    But I am using the esp-12 can you please tell me the codes and schematic for that on my gmail

  12. I’m using ESP8266-12e and finding it to be very unstable, sometimes it doesn’t boot well and I have to restart it, many times it completely pukes and dumps the stack. Is this normal for the 12e’s? I’ve worked with ESP8266-01’s and have not had this kind of instability. Any thoughts would be appreciated. Also, I can’t get the POST to work, it basically does nothing, but if I use GET code it works flawlessly. Does anyone have a sample of what the JSON POST should look like so I can make sure mine is right?

  13. Hi Rui,
    Would be possible to have it showing up in DOMOTICZ? If yes, how would be the code? Could you help? 🙂 Tks and congrats for the project!

  14. Great project! There is a problem I’ve found: if GPIO2 is low at boot time, the ESP-01 doesn’t boot, so you cannot boot the ESP while the door is open.

  15. Hi,

    is it possible to see the status of the door with no concern of getting a mail ?
    i want to monitor if a door is open after 4 pm in a school classroom and don’t care to see all the mails if it was open or closed during the day

    thanks
    ben

    • Yes, instead of triggering the email action every time the door closes, you can add an RTC to the ESP8266 (or check the time online).
      Then, it only trigger the email action if it’s after 4PM

  16. I am stuck. i have completed testing of maker app with my key , did the firmware flash -nodemcu firmware programmer, loaded sketch with my credentials (SSID,password,key). Connected the circuit as shown by you, but still cannt get the esp to trigger/send a msg to my gmail acc. i thing i did notice, after loading sketch, i tried sending AT commands through serial monitor, not getting an response back. Not sure were i went wrong. ( i am using 2 AA to power up my project)

      • yes, i can set a trigger through ifttt and receive a msg but with esp chip, it doesnt do anything. Connections are done as per your given circuit, but still it doesnt trigger. I can load the sketch through Ardunio on to esp chip , but later when connected to reed circuit, it powers up, but doesnt do anything. Also as mentioned earlier, i am not able to test the AT commands on the esp chip. is it normal ?

  17. Hello Rui,

    Congratulations with this project. I buy all the parts and replicate your project:)
    Everything is working good. But I buy the wrong switch, when I open the door
    I get the message “door closed” and the message “door open” when closed.
    Do I need to buy a other switch or can I alter something in the code?

    Rui, one more question: Can you alter the code, so I can use the same
    principle for my mailbox with a Microswitch instead? To receive only one
    message when the postman open the hatch. And maybe implement “Pushover”
    beside gmail. Very exciting!

    Kind regards,

    • Thanks for reading,
      Try switch the logic in my code to use give you the messages in reverse. I can’t create custom projects at the moment due to time constraints..

      Thanks,
      Rui

  18. It looks like GPIO2 will be low if the door is open during boot. Can you confirm? I might suggest to set serial to TX only and use GPIO3 (ESP RX) for the reed switch.

    • Nick, I have the same issue. Please read my previous comments.
      Try close and open one time fast. After it will be correct email. I can’t fix the sketch. We need “Simply read the current state of the reed switch”

      Now it changes email any time when was event and not depend on the state of the reed switch.

  19. Hello thanks for your post.
    I think is better to do work this project on battery ans use interupt To wake up esp8266 i see the esp8266 work with only few micro-amp.

    Sorry for my english i’m french.

  20. Can u plz check it once
    #include

    #include
    #include

    #include

    #define USE_SERIAL Serial

    #define trigPin 9
    #define echoPin 10
    #define piezoPin 8
    ESP8266WiFiMulti WiFiMulti;
    int normalDistance;
    boolean triggered = false;

    long duration, distance;

    void setup() {
    USE_SERIAL.begin(115200);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(piezoPin, OUTPUT);

    long duration, distance;

    while (millis() 0; t–) {
    USE_SERIAL.printf(“[SETUP] WAIT %d…\n”, t);
    USE_SERIAL.flush();
    delay(1000);
    }
    WiFiMulti.addAP(“hema”, “hema9966”);
    }
    }
    void loop() {

    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);

    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    duration = pulseIn(echoPin, HIGH);

    distance= duration*0.034/2;

    USE_SERIAL.print(“Distance: “);
    USE_SERIAL.println(distance);
    if (distance 0) {
    // HTTP header has been send and Server response header has been handled
    USE_SERIAL.printf(“[HTTP] GET… code: %d\n”, httpCode);

    // file found at server
    if(httpCode == HTTP_CODE_OK) {
    String payload = http.getString();
    USE_SERIAL.println(payload);
    }
    } else {
    USE_SERIAL.printf(“[HTTP] GET… failed, error: %s\n”, http.errorToString(httpCode).c_str());
    }

    http.end();
    }
    }
    }

    ultrasonic and buzzer are working in (Tools <board<Arduino/Generic uno)
    and wifi module is working in onlt(Tools <board<(any esp8266 in down column)
    when i mix ultrasonic and buzzer nothing happening)
    any idea
    thanks

  21. Has anyone tried this project using the Witty board? I’ve built it using the board shown, and it works, but would like to expand it using a Witty to send light levels.

  22. awsome with some -01 projects.
    would it require a lot if the unit should go deepsleep and awake on the magnets seperating? then send the IFTTT and go back to sleep again?

  23. Great tutorial, thank you. Is it possible to connect more then one ESP8266 to applet so I can monitor all my doors in my house. Do I need to change door_status but use the same key?

    • You could use the same applet and the same API key in all your devices.
      In your post request you could pass a value that would indicate in the value which ESP posted that event…

  24. Looks like a fun project. I am really new to this type of connection to the web so I am not too knowledgeable on some of the details. On the final schematic I do not see a power source. What voltage is required and how it it connected?

  25. Good morning: Thanks for your project. When I replace the password in the web address it says “Congratulations! You’ve fired the door_status event” but I do not receive the email. I do not know how to do it to receive it.

    • Hi Braian.
      Did you test your IFTTT applet before uploading the code?
      If you’re not receiving an email, it may be a problem with your applet.

  26. Exactly, until I get the text “” Congratulations! You’ve fired the door_status event “but I never receive the email in gmail. Please do not know how to continue

    • Hi again.
      In your IFTTT account, go to “Activity” in the following link: ifttt.com/activity
      Make sure your applet is turned on. Also, in the “Activity” section, you can see if something is wrong with that specific applet.
      It may tell you why it is not sending the email.
      I hope this helps.

    • Hi. We’re using esp8266-01, and we are using GPIO2.
      If you want to use that esp8266, you need to use GPIO2(pin marked with D4).
      I hope this helps.
      Regards,
      Sara 🙂

  27. This is great. Can you use deepsleep on this for those running off batteries? Also use mqtt instead of email? I have the ESP8266–01

  28. for me it’s not working,

    it is triggering the url from ESP, but when i trigger the url from the browser, it’s working for me.

    Please help me.

  29. Hi Rui,
    Why, am not getting enough mail notifications of this project, when am testing by URL, it shows congratulations ,n fire it but mail not receiving.
    Pl send me reply by my mail
    Thank you,

  30. Hi Rui Santos,

    Dear I m getting error, when event is triggered from my laptop & the email is not sent to my mail box at given email address. Web browser message ” Congratulations! You’ve fired the door_status event ” is OK.
    In activity window I get Action Skipped Error.
    Action skipped after 5 action errors.

    Please help me to resolve this problem.
    Thanks & kind regards,

    Yawar Saeed

    • Hi.
      Did you test the applet? Did it worked well?
      Don’t forget that you need to insert your own API key on the following line:
      const char* apiKey = “YOUR_IFTTT_API_KEY”;

      Regards,
      Sara 🙂

  31. I have similar setup using esp-8266-12 setup to email me using IFTTT when garage door changes from open to close or close to open. What I would like is can one esp-8266 communicate to another esp-8266 over my home wifi? They are too far apart to communicate directly. I want the second esp-8266 to then send hardwired signal to my home security system on the garage door status. Thanks.

  32. Hey Sara and Rui!

    Thanks for this very easy tutorial! Its my first project with an ESP-01 at all and I got the ESP programmed in unter 2h, inc. communication to the serial monitor stating the connection to Wifi and the triggering of the IO (just connecting it to 3.3V).

    Also triggering the IFTTT applet to send a mail to my inbox works via my browser!

    But doing it via the ESP does not work. Is there any configuration neccessary on my router to allow the ESP going through?

    KR
    Maik

    • Hi Maik.
      Thank you for reaching out.
      The only thing you need to do is to include your network connections (SSID and password) on the code and insert your own unique API key on the code.
      We haven’t done any other configurations.
      Are you getting any errors on the serial monitor?
      In your IFTTT account, you can go to “Activity” to see if the IFTTT is receiving your request.
      Regards,
      Sara

  33. This is really useful. I’m stuck with IFTTT – I get the website confirmation but no emails to me gmail account. Any suggestions?

  34. Using the Documentation tab in Webhooks I am able to sen a test email to my gmail account using door_status in the event box. Just not working from the esp8266. The serial monitor reports opening, closing and connection to ifttt.com.

    • Hi.
      replace this line on the code
      const char* host = “maker.ifttt.com”;

      with
      const char* host = “http://maker.ifttt.com”;

      I haven’t tested it, but it should solve the problem.
      Let me know if it works.
      Regards,
      Sara

  35. Hi, great tutorial! Please can you tell me why are you using resistor? Can it be done without resistor? And can it be done with Wemos D1 mini instead of esp8266? 🙂 Thanks!

    • Hi Timothy.
      Yes, you can use a wemos d1 mini instead.
      You can use the circuit without resistor, however, you’ll be more likely to have false positives.
      Regards,
      Sara

  36. Hi

    I trying this on my wemos d1 mini, not getting there quite yet 🙂 I just wonder where to add my magnetic reed switch?

    What/where is int pin = 2; for reed switch? I got the notification in my web browser (pc) but no mail either pc or phone.

    Which magnetic reed to use, NO or NC?

  37. Hi

    I guess this is why : “Triggers for the Gmail service are inactive”

    status.ifttt.com/incidents/0pb2pp4l3bx1

    Frode

  38. Hi,

    Confirmed – IFTTT has disabled the trigger for Gmail.

    Gmail actions may fail for some users

    Identified – The issue has been identified and a fix is being worked on. It will require a large rework in how Gmail is implemented, we appreciate your patience as we get Gmail up and running for everyone.
    May 15, 16:51 PDT

    • Hi.
      It seems that the Gmail option is temporarily not working. I’ve tested and it is not working for me either. There is a problem with the gmail services on IFTTT at the moment.
      However, there is an alternative.
      When you’re creating a new applet, after clicking the “that” word. Instead of searching for gmail, search for “email” and select the “email” option.
      Then select the “Send me an email” option. Proceed as described in the tutorial then. That worked for me a few days ago.
      Thanks.
      Regards,
      Sara

  39. Good day,
    I am struggling to get notifications from this event. Is there a workaround to get notifications to a gmail account?
    I tried your alternative suggestion, but without success.

    Thank you for great projects!

    Kind regards
    Louis

Leave a Comment

Download our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.