ESP8266 NodeMCU Door Status Monitor with Telegram Notifications

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 a message in your Telegram account whenever the door changes state: opened or closed. As long as you have access to the internet on your smartphone, you’ll be notified no matter where you are. The ESP8266 board will be programmed using Arduino IDE.

ESP8266 NodeMCU Door Status Monitor with Telegram Notifications Arduino IDE

We have a similar tutorial that sends emails instead of Telegram messages:

Read the ESP32 Guide: Door Status Monitor with Telegram Notifications

Project Overview

In this project, we’ll create a Telegram Bot that will send messages to your Telegram account whenever a door changes state. To detect the change, we’ll use a magnetic contact switch.

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

Introducing Telegram

Telegram Messenger is a cloud-based instant messaging and voice over IP service. You can easily install it on your smartphone (Android and iPhone) or computer (PC, Mac, and Linux). It is free and without any ads. Telegram allows you to create bots that you can interact with.

Telegram logo

Bots are third-party applications that run inside Telegram. Users can interact with bots by sending them messages, commands, and inline requests. You control your bots using HTTPS requests to Telegram Bot API“.

The ESP8266 will interact with the Telegram bot to send messages to your Telegram account. Whenever the door changes state, you’ll receive a notification on your smartphone (as long as you have access to the internet).

Creating a Telegram Bot

Go to Google Play or App Store, download, and install Telegram.

Install and Download Telegram

Open Telegram and follow the next steps to create a Telegram Bot. First, search for “botfather” and click the BotFather as shown below. Or open this link t.me/botfather on your smartphone.

botfather

The following window should open, and you’ll be prompted to click the start button.

Telegram Start BotFather to Create a new Bot

Type /newbot and follow the instructions to create your bot. Give it a name and username. Mine is called Door Sensor, and the username is ESPDoorSensorBot.

Telegram BotFather Create a New Bot

If your bot is successfully created, you’ll receive a message with a link to access the bot and the bot token. Save the bot token because you’ll need it so that the ESP8266 can interact with the bot.

Telegram BotFather Get Bot Token

Sending a Message to the Bot

This step is very important. Don’t miss it. Otherwise, the project will not work.

You must send a message to your Telegram Bot from your Telegram account before it can send you messages.

1) Go back to the chats tab, and in the search field, type the username of your bot.

Telegram searching for ESP32 bot

2) Select your bot to start a conversation.

3) Click on the Start link.

Star conversation with Telegram Bot

And that’s it! You can proceed to the next section.

Get Your Telegram User ID

To send a message to your Telegram account, the bot needs to know your user ID.

In your Telegram account, search for “myidbot” or open this link t.me/myidbot on your smartphone.

Telegram Get Chat ID with IDBot

Start a conversation with that bot and type /getid. You will get a reply back with your user ID. Save that user ID, because you’ll need it later in this tutorial.

Telegram Get Chat ID with IDBot getid

Preparing Arduino IDE

We’ll program the ESP8266 board using Arduino IDE, so make sure you have it installed in your Arduino IDE.

Universal Telegram Bot Library

To interact with the Telegram bot, we’ll use the Universal Telegram Bot Library created by Brian Lough that provides an easy interface for the Telegram Bot API.

Follow the next steps to install the latest release of the library.

  1. Click here to download the Universal Arduino Telegram Bot library.
  2. Go to Sketch > Include Library > Add.ZIP Library...
  3. Add the library you’ve just downloaded.

Important: don’t install the library through the Arduino Library Manager because it might install a deprecated version.

For all the details about the library, take a look at the Universal Arduino Telegram Bot Library GitHub page.

ArduinoJson Library

You also have to install the ArduinoJson library. Follow the next steps to install the library.

  1. Go to Skech > Include Library > Manage Libraries.
  2. Search for “ArduinoJson”.
  3. Install the library.

We’re using ArduinoJson library version 6.15.2.

Install in Arduino IDE the ArduinoJSON library

Parts Required

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 with Reed Switch

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

Schematic Wiring Diagram ESP8266 with Reed Switch

Code

Copy the sketch below to your Arduino IDE. Replace the SSID, password, BOT token, and user ID with your credentials.

/* 
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp8266-nodemcu-door-status-telegram/
  
  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>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.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";

// Initialize Telegram BOT
#define BOTtoken "XXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"  // your Bot Token (Get from Botfather)

// Use @myidbot to find out the chat ID of an individual or a group
// Also note that you need to click "start" on a bot before it can
// message you
#define CHAT_ID "XXXXXXXXXX"

X509List cert(TELEGRAM_CERTIFICATE_ROOT);
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);

// 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);
  configTime(0, 0, "pool.ntp.org");      // get UTC time via NTP
  client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org
  

  // 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.mode(WIFI_STA);
  WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("");
    Serial.println("WiFi connected");  

    bot.sendMessage(CHAT_ID, "Bot started up", "");
}

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 notification
        bot.sendMessage(CHAT_ID, "The door is " + doorState, "");
    }  
  }
}

View raw code

How the Code Works

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

First, include the required libraries.

#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.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 Telegram Bot Token—the one you’ve gotten in this step.

#define BOTtoken "XXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

Insert your chat ID—the one you’ve gotten in this step.

#define CHAT_ID "XXXXXXXXXX"

Create a new Wi-Fi client with WiFiClientSecure.

X509List cert(TELEGRAM_CERTIFICATE_ROOT);
WiFiClientSecure client;

Create a bot with the token and client defined earlier.

UniversalTelegramBot bot(BOTtoken, client);

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 a message to your Telegram account).

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

Add a root certificate for api.telegram.org.

client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org

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 and 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.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");  

Send a message to your Telegram account informing you that the bot started.

bot.sendMessage(CHAT_ID, "Bot started up", "");

loop()

In the loop(), we’ll read the changeState variable, and if a change has occurred, we’ll send a message to your Telegram account.

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 line sends a notification to your Telegram account with the current door state.

bot.sendMessage(CHAT_ID, "The door is " + doorState, "");

Demonstration

After modifying the sketch to include your network credentials, bot token, and user ID, 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.

ESP8266 NodeMCU Door Sensor Monitoring Serial Monitor.

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 receive a message in your Telegram account.

ESP32 ESP8266 Door Sensor Telegram Bot Demonstration

Wrapping Up

In this tutorial, you’ve learned how to send notifications to your Telegram account when the reed switch changes state. This can be useful to detect if a door, window, or drawer was opened or closed.

We have similar tutorials that you may like:

Learn more about the ESP8266 with our resources:

Thanks for reading.



Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »

Build Web Server projects with the ESP32 and ESP8266 boards to control outputs and monitor sensors remotely. Learn HTML, CSS, JavaScript and client-server communication protocols DOWNLOAD »


Enjoyed this project? Stay updated by subscribing our newsletter!

22 thoughts on “ESP8266 NodeMCU Door Status Monitor with Telegram Notifications”

  1. Hi Rui thanks for another wonderful project I am going to have a go at making this for my front door with an esp8266-01 and wired reed switch plus a 3.2V LiFePO4, 14500 battery please let me know if that all sounds ok.

    Thanks Bob

    Reply
  2. So I followed this project and all works with the exception of Telegram notifications. On telegram: I have my garage door bot screen up , /getid (inserted into my program and then sent it to my ESP8266 , /start.
    I am using Iphone12 , ide 1.8.16. , (Windows store 1.8.51.0.) on monitor I can see the state of the switch change so my circuit has to be correct. What am I missing here?
    Another question ; I am using a ESP D1 mini and would like to power it with a pair od repurposed solar cells. How would I attach solar cells to mini short of butchering a USB cable?

    Reply
  3. So if I were to use a ESP12-F Doiting ,what would I need to change in the code to make it work correctly? Using the code as it is ,is not stable, for instance on my breadboard I have made the connection(simple), if I jumper the connection to imitate a magnetic switch led is on then I get a response that the door is open then closed , remove the jumper it again does the same , door is open then closed.
    Thanks

    Reply
  4. Hello,
    Great project.
    As I will be going to battery Power how about implementing deep sleep and wake up by interrupt?
    Any examples ready?

    Thanks

    Reply
  5. HI Rui

    I’m just getting back into playing with Arduino’s etc, on this project I am hitting a compiling problem, please see below. Arduino IDE is 2.0.0-beta.12

    C:\Users\user\Documents\Arduino\Door sensor\Door sensor.ino:32:1: error: ‘X509List’ does not name a type
    X509List cert(TELEGRAM_CERTIFICATE_ROOT);
    ^
    C:\Users\user\Documents\Arduino\Door sensor\Door sensor.ino: In function ‘void setup()’:
    C:\Users\user\Documents\Arduino\Door sensor\Door sensor.ino:46:10: error: ‘class axTLS::WiFiClientSecure’ has no member named ‘setTrustAnchors’
    client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org
    ^
    C:\Users\user\Documents\Arduino\Door sensor\Door sensor.ino:46:27: error: ‘cert’ was not declared in this scope
    client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org
    ^
    Compilation error: Error: 13 INTERNAL: exit status 1

    Any help is really appreciated

    Cheers

    Phil

    Reply
  6. Thank you so much with this wonderful well explain tutorial. We hope that one day Rui will make the telegram project with TTGO SIM800L ESP32. So that one would deploy it any where without concerning about WiFi availability. Thank you so much indeed.

    Reply
  7. Has anyone had problems with signal bounce. Finally got this working after resolving a few issues, some were related to ESP-12 F . I have tried this and it works on both ESP 8266 and ESP -12F . Also both report a double reading. Upon door open it shows door open then close on both devices.Why am I getting what seems to be a bounced signal?

    Reply
  8. Hello, Your project is very interesting; also could you make it evolve by having the ability to remotely control an unmaintained relay? With this additional possibility, one could open or close a door remotely while having the feedback that the door is open or closed. With my thanks for your help and maybe, this will be one of your new projects?
    Best regards. Jean Yves

    Reply
      • Hello, thank you for your answer, but before combining these files, I am unable to download the “Universal Arduino Telegram Bot Library” version 6.5.12. She does not exist. There is 6.5.0 -beta then 6.6.0-beta ….. until 6.18.5. Can you give me a link that points to this bookstore? I have tested with several of these versions but I am having errors. I thank you in advance. Sincerely, Jean-Yves

        Reply
        • I’m sorry for the previous post. in fact you wrote that the version to use is “6.5.12”. I discovered by looking closely at your “library manager” window that it was version 6.15.2. I have now installed it. But now when compiling I have this message: “libraries / Universal-Arduino-Telegram-Bot-master / src / TelegramCertificate.h: 9: 12: error: ‘const char TELEGRAM_CERTIFICATE_ROOT [1369]’ previously defined here
          const char TELEGRAM_CERTIFICATE_ROOT [] = R “= EOF = (
          ^
          exit status 1
          Compilation error for the Generic ESP8266 Module board ”

          Can you tell me where this error came from? Thank you again for your help. Best regards. Jean Yves

          Reply
          • Hi.
            One of our readers shared the following. I hope that helps.
            “Note that on the ESP8266 it only works for me on Arduino ESP8266 firmware boards version 2.7.4”
            Regards,
            Sara

          • Hello Sara,
            Yes, now it is working perfectly. Note that the switch was not detected; I had to put a resistance in “pull up” and not in “pull down”. From that moment it started to work but the switch generated many bounces. I modified the “delay” but little change. So I added a 2.2 microfarad capacitor parallel to the switch and now it’s OK. Note that we could use a flip-flop made from two NAND gates of an integrated circuit of the CD4093 type but that complicates a little. Thank you for your explanations. Continue like this, your information is very interesting. Sincerely, Jean-Yves

  9. Hello Sara,
    I tried the sketch with ESP32 and it works ok,
    but with the D1 Mini Pro card it does not communicate with Telagram.
    It does not even send ” Bot started up”.
    What could it be?
    Thank a lot
    Giuseppe

    Reply
      • Hi Sara,
        thanks for your quick answer.
        I do not get any errors.
        On the serial monitor I get the correct answer, also the LED works correctly but I do not get communication with the Telegram BOT.
        The ESP32 sketch works fine with the same CHAT_ID and BOT_token.
        I decided to use the ESP32.
        Thanks a lot
        regards Giuseppe

        Reply

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.