Door Status Monitor using ESP8266 with Email Notifications

Using an ESP8266 NodeMCU board and a magnetic reed switch, you'll door status monitor in this project. When the status of the door changes from open to closed, you'll receive an email notification. IFTTT will be used to send email notifications, and the ESP8266 board will be programmed using the Arduino IDE.

You may use an SMTP server instead of sending email notifications with IFTTT. You may follow the next instruction to learn how to send emails using your ESP8266 and an SMTP server:

Send Email from ESP8266 NodeMCU via SMTP Server: HTML, Text, and Attachments (Arduino)

lilygo Official Store

You may also send notifications to your Telegram account if you wish. In the following tutorial, you will learn how to use Telegram with the ESP8266: SOON.

Project Overview

You will receive an email notification anytime a door changes status in this project. We'll use a magnetic contact switch to detect the change. IFTTT will be used to send an email.

A magnetic contact switch is essentially a reed switch that has been encased in a plastic shell so that it may be easily applied to a door, window, or drawer to detect whether the door is open or closed.

reed switch door status monitor sensor

When a magnet is near the switch, the electrical circuit is closed (the door is closed). The circuit is open when the magnet is far away from the switch (the door is opened). Please see the figure below.

magnetic reed switch howitworks

To detect changes in the state of the Reed switch, we may connect it to an ESP8266 GPIO.

keyestudio Official Store

Sending Emails with IFTTT

A free email service called “IFTTT“, which stands for “If This Then That“, will be used to send emails using the ESP8266.

IFTTT is a platform that allows you to have creative control over a variety of products and apps. Apps may be made to work in tandem. Sending a certain request to IFTTT, for instance, triggers an applet that makes something happen, like sending you an email alert.

Once you understand how it works, the IFTTT service is easy to use. I like it. However, I'm not too fond of the layout of their website, which is continuously changing.

Currently, you can have three active applets running simultaneously in the free version.

Creating an IFTTT Account

Creating an account on IFTTT is free!

Go to the official website at https://ifttt.com and click the Get Started button at the top of the page, or sign up if you don't already have an account.

TSCINBUNY Official Store

door-status-monitor-using-esp8266

Creating an Applet

First, you'll need to create an applet in IFTTT. An applet connects two or more apps or devices (like the ESP8266 and sending email).

Applets are composed of triggers and actions.

  • Triggers tell an applet to begin. The ESP8266 will submit a request (webhooks) that will cause the applet to be triggered.
  • Actions are the ultimate result of running an applet. In our instance, sending an email was sufficient.

To create your applet, follow the instructions below.

1- Click on this link to start creating an Applet.

2- Click on the Add button.

Create applet email step 1 ifttt

3- Search for “Webhooks” and select it.

Create applet email step 2

4- Select the option “Receive a web request“.

Create applet email step 3

5- Enter the event name, such as door_status. You may call it anything you like, but if you do, you'll also need to change it in the code given later on.

Create applet email step 4

6- Then, under the “Then That” menu, you need to click the Add button to select what happens when the previous event triggers.

Create applet email step 5

7- Search for email and select the email option.

Create applet email step 6

8- Click on Send me an email.

Create applet email step 7

9- Then, write the email's subject and body. You can leave the default message or change it to whatever you want. The {{EventName}} is a placeholder for the event name; in this case, it’s door_status. The {{OccuredAt}} is a placeholder for the timestamp of when the event was triggered. The {{Value1}} is a placeholder for the actual door status. So, you can play with those placeholders to write your own message. When you’re done, click on Create action.

Create applet email step 8

10- Now, you can click on Continue.

Create applet email step 9

11- Finally, click on Finish.

Create applet email step 10 f

12- You’ll be redirected to a similar page, as shown below.

Create applet email step 11 f

Your Applet was successfully created. Now, let’s test it.

Testing your Applet

Open the “Documentation” page by going to the URL: https://ifttt.com/maker_webhooks.

You'll be sent to a website where you can test it out by triggering an event and accessing your API key (highlighted in red). You'll need your API key later, so save it safely.

IFTTT Trigger Event 1

Let us now test the {event} by triggering it. Write the previous event you made in the placeholder event. It is door_status in our situation. Additionally, provide a value in the value1 box, such as open. After that, click the Test It button.

IFTTT Trigger Event Testing Applet

You should get an email informing you that the event has been activated as well as a success message saying “Event has been triggered” in your inbox.

Received Email IFTTT Event Triggered

If you received the email, your Applet is working normally. You are now free to proceed to the next stage. When the door changes states, we'll program the ESP8266 to trigger your Applet.

Hardware List

This is the hardware you'll need to complete this project:

You can use the preceding links to find all the parts for your projects at the best price!

Schematic: ESP8266 NodeMCU with Reed Switch

The reed switch was wired to GPIO 4 (D2), but it may be connected to any suitable GPIO.

ESP8266 Reed Switch door sensor circuit

Code

Copy and paste the sketch below into your Arduino IDE. Change the SSID, password, and IFTTT API key with your own.

/*********
  LEDEdit PRO
  Complete project details at https://lededitpro.com/door-status-monitor-using-esp8266-with-email-notifications/
  
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*********/

#include <ESP8266WiFi.h>

// Set GPIOs for LED and reedswitch
const int reedSwitch = 4;
const int led = 2; //optional

// Detects whenever the door changed state
bool changeState = false;

// Holds reedswitch state (1=opened, 0=close)
bool state;
String doorState;

// Auxiliary variables (it will only detect changes that are 1500 milliseconds apart)
unsigned long previousMillis = 0; 
const long interval = 1500;

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
const char* host = "maker.ifttt.com";
const char* apiKey = "REPLACE_WITH_YOUR_IFTTT_API_KEY";

// Runs whenever the reedswitch changes state
ICACHE_RAM_ATTR void changeDoorStatus() {
  Serial.println("State changed");
  changeState = true;
}

void setup() {
  // Serial port for debugging purposes
  Serial.begin(115200);

  // Read the current door state
  pinMode(reedSwitch, INPUT_PULLUP);
  state = digitalRead(reedSwitch);

  // Set LED state to match door state
  pinMode(led, OUTPUT);
  digitalWrite(led, state);
  
  // Set the reedswitch pin as interrupt, assign interrupt function and set CHANGE mode
  attachInterrupt(digitalPinToInterrupt(reedSwitch), changeDoorStatus, CHANGE);

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");  
}

void loop() {
  if (changeState){
    unsigned long currentMillis = millis();
    if(currentMillis - previousMillis >= interval) {
      previousMillis = currentMillis;
      // If a state has occured, invert the current door state   
      state = !state;
      if(state) {
        doorState = "closed";
      }
      else{
        doorState = "open";
      }
      digitalWrite(led, state);
      changeState = false;
      Serial.println(state);
      Serial.println(doorState);
        
      //Send email
      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=" + doorState + "\r\n");
    }  
  }
}

The ESP8266 board add-on must be installed in your Arduino IDE. Follow the next instruction if you don't:

Install ESP8266 Board in Arduino IDE in less than 1 minute

How the Code Works

To learn how the code works, continue reading or proceed to the Demonstration section.

In order for the ESP8266 to connect to your network and interact with the IFTTT services, you need to first include the ESP8266WiFi library.

#include <ESP8266WiFi.h>

Set the GPIOs for the reed switch and LED (GPIO 2 is the onboard LED). If the door is open, we'll light up the on-board LED.

const int reedSwitch = 4;
const int led = 2; //optional

The boolean variable changestate specifies whether or not the door's status has changed.

bool changeState = false;

The state variable will hold the reed switch and doorState, as the name implies, will hold the door state—closed or open.

bool state;
String doorState;

We may debounce the switch using the following timer variables: Only modifications that occurred with a time difference of at least 1500 milliseconds will be considered.

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

For the ESP8266 to connect to the internet, provide your SSID and password in the following variables:

const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";

Fill in the apiKey variable with your personal IFTTT API key, which you obtained in this step.

const char* apiKey = "REPLACE_WITH_YOUR_IFTTT_API_KEY";

Whenever a change in the door state is detected, the changeDoorStatus() function will run. The changeState a variable is simply changed to true by this function. Then, in loop(), we'll deal with what occurs when the state changes (inverting the previous door state and sending an email).

ICACHE_RAM_ATTR void changeDoorStatus() {
  Serial.println("State changed");
  changeState = true;
}

setup()

In the setup(), initialize the Serial Monitor for debugging purposes:

Serial.begin(115200);

Set the reed switch as an INPUT. And save the current state when the ESP8266 first starts.

pinMode(reedSwitch, INPUT_PULLUP);
state = digitalRead(reedSwitch);

Set the LED as an OUTPUT and set its state to match the reed switch state (circuit closed and LED off; circuit opened and LED on).

pinMode(led, OUTPUT);
digitalWrite(led, state);
  • door closed –> the ESP8266 reads a HIGH signal –> turn off on-board LED (send a HIGH signal*).
  • door open –> the ESP8266 reads a LOW signal –> turn on on-board LED (send a LOW signal*).

Send a HIGH signal to turn the ESP8266 on-board LED off and a LOW signal to turn it on. This is how inverted logic works.

Setting an interrupt

Set the reed switch as an interrupt.

attachInterrupt(digitalPinToInterrupt(reedSwitch), changeDoorStatus, CHANGE);

In the Arduino IDE, you use the attachInterrupt() function to set an interrupt, which receives as parameters the GPIO interrupt pin, the name of the function to be called, and the mode.

A GPIO interrupt is the first argument. To set the actual GPIO as an interrupt pin, use digitalPinToInterrupt(GPIO).

The attachInterrupt() function's second argument is the name of the function that will be called every time the interrupt is triggered: the interrupt service routine (ISR). It is the changeDoorStatus function in this case.

The ISR function should be as simple as feasible so that the processor may return to the main program execution as soon as possible.

The mode is the third argument. We set it to CHANGE so that the interrupt is triggered anytime the pin's value changes, such as from HIGH to LOW or LOW to HIGH.

Initialize Wi-Fi

The following lines connect the ESP8266 to Wi-Fi.

WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");  

loop()

In loop(), we’ll read the changeState variable, and if a change has occurred, we’ll send an email using IFTTT.

First, check if a change occurred:

if (changeState){

Then, check if at least 1500 milliseconds have passed since the last state change.

if(currentMillis - previousMillis >= interval) {

If that’s true, reset the timer and invert the current switch state:

state = !state;

If the reed switch state is 1(true), the door is closed. So, we change the doorState variable to closed.

if(state) {
  doorState = "closed";
}

If it’s 0(false), the door is opened.

else{
  doorState = "open";
}

Set the LED state accordingly and print the door state in the Serial Monitor.

digitalWrite(led, state);
changeState = false;
Serial.println(state);
Serial.println(doorState);        

Finally, the following lines make a request to IFTTT with the current door status on the event (door_status) that we created previously.

// Send email
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=" + doorState + "\r\n");

When IFTTT receives this request, it will trigger the action to send an email.

Demonstration

Upload the sketch to your ESP8266 after modifying it to include your API key and network credentials. Select your ESP8266 board from the Tools > Board menu. Then, go to Tools > Port and select the COM port to which the ESP8266 is attached.

To check whether the changes are detected and the ESP8266 can connect to IFTTT, open the serial monitor at a baud rate of 115200.

ESP8266 Connect IFTTT Door Change State

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

door-status-monitor-using-esp8266

Now, when someone opens or closes your door, you get notified via email.

Received Email IFTTT Event Triggered Door Closed

Conclusion

In this tutorial, you learned how to trigger an event when the reed switch changes state. This is useful for detecting if a door, window, or drawer has been opened or closed. You've also learned how to use IFTTT to send an email whenever an event is triggered.

We hope you find this tutorial useful. Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *

ESP8266 Home Automation Projects

Leverage the power of this tiny WiFi chip to build exciting smart home projects