ESP8266 NodeMCU Door Status Monitor with Email Notifications (IFTTT)

 In this project, you’re going to monitor the status of a door using an ESP8266 NodeMCU board and a magnetic reed switch. You’ll receive an email notification whenever the door changes state: opened or closed. The email notifications will be sent using IFTTT, and the ESP8266 board will be programmed using Arduino IDE.

ESP8266 NodeMCU Door Status Monitor with Email Notifications IFTTT Arduino IDE

Instead of sending email notifications with IFTTT, you can use an SMTP server instead. To learn how to send emails with your ESP8266 using an SMTP server, you can follow the next tutorial:

If you prefer, you can also send notifications to your Telegram account. Learn how to use Telegram with the ESP8266 on the following tutorial:

We have a similar tutorial for the ESP32 board: Door Status Monitor with Email Notifications (IFTTT)

Project Overview

In this project, you’ll send an email notification whenever a door changes state. To detect the change, we’ll use a magnetic contact switch. To send an email we’ll use IFTTT.

A magnetic contact switch is basically a reed switch encased in a plastic shell so that you can easily apply it to a door, a window, or a drawer to detect if the door is open or closed.

magnetic contact switch reed switch

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

magnetic reed switch how i tworks

We can connect the reed switch to an ESP8266 GPIO to detect changes in its state.

Sending Emails with IFTTT

To send emails with the ESP8266, we’ll use a 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, sending a particular request to IFTTT triggers an applet that makes something happen, like sending you an email alert.

I like IFTTT service and once you understand how it works, it is easy to use. However, I’m not too fond of the layout of their website and the fact that it is constantly changing.

* currently, you can have three active applets simultaneously in the free version.

Creating an IFTTT Account

Creating an account on IFTTT is free!

Go to the official site: 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

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

Applets are composed of triggers and actions:

  • Triggers tell an Applet to start. The ESP8266 will send a request (webhooks) that will trigger the Applet.
  • Actions are the end result of an Applet 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, for example, door_status. You can call it any other name, but if you change it, you’ll also need to change it in the code provided later on.

IFTTT Create your applet receive a web request

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

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

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

Now, let’s trigger the event to test it. In the {event} placeholder, write the event you created previously. In our case, it is door_status. Additionally, add a value in the value1 field, for example open. Then, click the Test It button.

IFTTT testing your applet

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

IFTTT Applet tested successfully

If you received the email, your Applet is working as expected. You can proceed to the next section. We’ll program the ESP8266 to trigger your Applet when the door changes state.

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!

Schematic – ESP8266 NodeMCU with Reed Switch

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

Schematic ESP8266 NodeMCU with Reed Switch wiring circuit diagram

Code

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

/*********
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/door-status-monitor-using-the-esp8266/
  
  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");
    }  
  }
}

View raw code

You must have the ESP8266 board add-on installed in your Arduino IDE. If you don’t, follow the next tutorial:

How the Code Works

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

First, you need to include the ESP8266WiFi library so that the ESP8266 can connect to your network to communicate with the IFTTT services.

#include <ESP8266WiFi.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 state variable will hold the reed switch state and the doorState, as the name suggests, will hold the door state—closed or opened.

bool state;
String doorState;

The following timer variables allow us to debounce the switch. Only changes that have occurred with at least 1500 milliseconds between them will be considered.

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

Insert your SSID and password in the following variables so that the ESP8266 can 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 on 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 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*)

The ESP8266 on-board LED works with inverted logic—send a HIGH signal to turn it off and a LOW signal to turn it on.

Setting an interrupt

Set the reed switch as an interrupt.

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

To set an interrupt in the Arduino IDE, you use the attachInterrupt() function, which accepts as arguments: the GPIO interrupt pin, the name of the function to be executed, and mode.

The first argument is a GPIO interrupt. You should use digitalPinToInterrupt(GPIO) to set the actual GPIO as an interrupt pin.

The second argument of the attachInterrupt() function is the name of the function that will be called every time the interrupt is triggered – the interrupt service routine (ISR). In this case, it is the changeDoorStatus function.

The ISR function should be as simple as possible, so the processor gets back to the execution of the main program quickly.

The third argument is the mode. We set it to CHANGE to trigger the interrupt whenever the pin changes value – for example from HIGH to LOW or LOW to HIGH.

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

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

After modifying the sketch to include your network credentials and API key, upload it to your ESP8266. Go to Tools Board and select your ESP8266 board. Then, go to Tools Port and select the COM port the ESP8266 is connected to.

Open the Serial Monitor at a baud rate of 115200 to check if the changes are detected and if the ESP8266 can connect to IFTTT.

Testing ifttt with ESP8266 NodeMCU

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

Testing ifttt with ESP8266 NodeMCU

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

Door Status Received Email IFTTT ESP8266 NodeMCU

Watch the video demonstration

We recorded this video several years ago (I’m sorry for the bad quality).

No comments:

Post a Comment