ESP32 Door Status Monitor with Telegram Notifications

In this project, you’re going to monitor the status of a door using an ESP32 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 ESP32 board will be programmed using Arduino IDE.

ESP32 Door Status Monitor with Telegram Notifications Arduino IDE

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

Read the ESP8266 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 ESP32 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 png

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

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

We wired the reed switch to GPIO 4, 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, BOT token, and user ID with your credentials.

/* 
  Rui Santos
  Complete project details at https://RandomNerdTutorials.com/esp32-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 <WiFi.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"

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

  // 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);
  client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
  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 <WiFi.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 ESP32 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.

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

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

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 ESP32, read the following tutorial:

Initialize Wi-Fi

The following lines connect the ESP32 to Wi-Fi and add a root certificate for api.telegram.org.

WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org
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 ESP32. Go to Tools > Board and select your ESP32 board. Then, go to Tools > Port and select the COM port the ESP32 is connected to.

Open the Serial Monitor at a baud rate of 115200 to check if the changes are detected.

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

If you want to learn more about the ESP32, check our courses:

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!

16 thoughts on “ESP32 Door Status Monitor with Telegram Notifications”

  1. Hi,
    time ago you published a project to send a photo, triggered by a proximity sensor, a PIR, via telegram: i think you can update that using a reed switch insted of the PIR.
    regards

    Reply
  2. It seems that the code is not reading the state of the switch in the loop.
    Also, it’s not a good idea to put a print statement in the ISR. Just move it to the loop.

    I have this working through Telegram but I’ve never used Telegram before.
    I am developing a temp sensor device that needs to send alarm messages when the temp is above a threshold. Can the bot send a message to more people than just me?

    Reply
    • Hi.
      In this example, the switch is set as an interrupt.

      Yes, it can.
      You just need to add the user IDs that will receive the message.
      Additionally, before a user can receive a message from the bot, it must send a message to the bot first. Then, everything is fine.
      Alternatively, you can also create a group with several users that will receive the message. See this example: https://randomnerdtutorials.com/telegram-group-esp32-esp8266/
      I hope this helps.
      Regards,
      Sara

      Reply
      • Sara, Thanks for the reply. I discovered your group tutorial after I wrote my original message.
        I understand that the switch fires an interrupt but ISR only returns the state changed flag but not the state of the switch so the code depends on keeping the state value synchronized since reading the switch once at startup. It might be better to read the switch state on each interrupt to ensure it will always correspond to the actual state of the IO pin. I modified the my test version of the code to do that.

        Reply
  3. Can you make the home automation project using esp rainmaker Arduino library .and please address the wifi cred reset issue .

    Reply
  4. You can add a Delay before it kicks in, to give you time to leave the house.
    I would connect it to a UPS anyway, in case the thief cuts off the power.

    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.