Door Status Monitor using ESP32 with Email Notifications

Using an ESP32 board and a magnetic reed switch, you will use this project to monitor the status of a door. When the status of the door changes—from open to closed—you'll receive an email message. The ESP32 board will be programmed using the Arduino IDE, and the email notifications will be sent using IFTTT.

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 the ESP32 and an SMTP server:

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 ESP32:

lilygo Official Store

We have a similar tutorial for the ESP8266 board: Door Status Monitor using ESP8266 with Email Notifications

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 encased in a plastic shell so that it can be easily applied to a door, window, or drawer to detect whether the door is open or closed.

magnetic contact switch reed switch

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

magnetic reed switch how i tworks

We can connect the Reed switch to an ESP32 GPIO to detect changes in its state.

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 ESP32.

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 example, 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 simultaneously in the free version.

Creating an IFTTT Account

Creating an account on IFTTT is free!

TSCINBUNY Official Store

Visit the official website at https://ifttt.com/ and click the Get Started button at the top of the page, or Signup if you already have an account.

IFTTT Get Started Web Page

Creating an Applet

You need to first create an applet on IFTTT. An applet connects two or more devices or apps (like the ESP32 and email sending) together.

Applets are composed of triggers and actions:

  • Triggers tell an Applet to start. The ESP32 will send a request (webhooks) that will trigger the Applet.
  • Actions are the result of an applet's run. In our case, sending an email.

Follow the next instructions to create your applet.

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

2) Click on the “Add” button.

IFTTT Create your applet

3) Search for “Webhooks” and select it.

IFTTT Create your applet choose a service

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

IFTTT Create your applet webhooks receive a web request

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.

IFTTT Create your applet receive a web request

6) To select what happens after the previous event is triggered, you need to click the “Add” button on the “Then that” menu.

IFTTT Create your applet create your own

7) Search for email and select the email option.

IFTTT Create your applet choose a service email

8) Click on Send me an email.

IFTTT Create your applet choose an action

9) Then, write the subject and content of the email. You may leave the default message or change it to anything else. The {{EventName}} is a placeholder for the event name, which is door_status in this instance. The {{OccuredAt}} field is a placeholder for the timestamp of when the event occurred. The {{Value1}} placeholder represents the real door status. To write your message, you may play with the placeholders. When you're finished, click “Create action“.

IFTTT Create your applet eventName set action fields

10) Now, you can click on “Continue“.

IFTTT Create your applet create your own

11) Finally, click on “Finish“.

IFTTT Create your applet review and finish

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

IFTTT Create your applet connected

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

Testing your Applet

Go to this URL: https://ifttt.com/maker_webhooks and open the “Documentation” tab.

You’ll access a web page where you can trigger an event to test it and get access to your API key (highlighted in red). Save your API key to a safe place because you’ll need it later.

IFTTT testing your applet

Let's try to trigger the {event} now and test it. Write the previous event you created in the placeholder field. It is door_status in our case. Additionally, add a value, such as “open“, to the value1 field. Click the “Test It” button when you're done.

IFTTT testing your 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.

IFTTT Applet tested successfully

If you received the email, your applet is working as expected. You may proceed to the next section now. Because of the programming, we'll execute on the ESP32, your Applet will be activated when the door changes states.

Parts 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 – ESP32 with Reed Switch

We wired the reed switch to GPIO 4, but you can connect it to any suitable GPIO.

Schematic ESP32 with Reed Switch wiring circuit diagram

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://RandomNerdTutorials.com/door-status-monitor-using-esp32-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 <WiFi.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 ESP32 board add-on must be installed in your Arduino IDE. Follow the next instruction if you don't:

How the Code Works

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

You must first include the WiFi library to enable the ESP32 to connect to your network and communicate with the IFTTT services.

#include <WiFi.h>

Set the GPIOs for the reed switch and LED (the on-board LED is GPIO 2). We’ll light up the on-board LED when the door is open.

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

The changeState boolean variable indicates whether the door has changed state.

bool changeState = false;

The Reed switch will hold the state variable and the doorState will hold the door closed or open, as the name suggests.

bool state;
String doorState;

We may debounce the switch using the following timer variables. The only changes that will be taken into account are those that have occurred with at least 1500 milliseconds between them.

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

The following variables must include your SSID and password for the ESP32 to connect to the internet:

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

Insert your own IFTTT API key on the apiKey variable—the one you’ve gotten in this step.

const char* apiKey = "REPLACE_WITH_YOUR_IFTTT_API_KEY";

The changeDoorStatus() function will run whenever a change is detected in the door state. This function simply changes the changeState variable to true. Then, in the loop() we’ll handle what happens when the state changes (invert the previous door state and send 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 ESP32 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);

Setting an interrupt

Set the reed switch as an interrupt.

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

The attachInterrupt() function in the Arduino IDE is used to set an interrupt. It takes three arguments: mode, the name of the function to be run, and the GPIO interrupt pin.

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

The interrupt service routine (ISR), which will be called each time the interrupt is triggered, is named as the second argument to the attachInterrupt() function. The changeDoorStatus function is used in this case.

For the processor to swiftly return to the main program's execution, the ISR function should be as simple as feasible.

The mode is the third argument. To set the interrupt to be triggered anytime the pin's value changes, such as going from HIGH to LOW or LOW to HIGH, we set it to CHANGE.

To learn more about interrupts with the ESP32, read the following tutorial:

Initialize Wi-Fi

The following lines connect the ESP32 to Wi-Fi.

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

loop()

In the 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 the IFTTT receives this request, it will trigger the action to send an email.

Demonstration

Upload the modified sketch to your ESP32 after modifying it to include your API key and network credentials. Select your ESP32 board from the Tools > Board menu. After that, select the COM port the ESP32 is attached to under Tools > Port.

To check whether the changes are detected and if the ESP32 can connect to IFTTT, open the Serial Monitor at a baud rate of 115200.

Testing ifttt with ESP32

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

Testing ifttt with ESP32

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

Door Status Received Email IFTTT ESP32

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.

Instead of sending an email, you may want to send a message to Telegram, for example.

If you like ESP32, you may also like:

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

Oh hi there It’s nice to meet you.

Sign up to receive awesome content in your inbox, every month.

We don’t spam! Read our privacy policy for more info.

Leave a Reply

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

Developing IoT Projects with ESP32

Automate your home or business with inexpensive Wi-Fi devices