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.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

46 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

      • 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
  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
    • Hello,

      I was experiencing the same issue as Guiseppe. On my Wemos D1 Mini, the message “Bot started up” would not send to my Telegram bot. I found that I had to add the following line of code at the top of the void setup() function: configTime(0, 0, “pool.ntp.org”);

      After I add the line, the message “Bot started up” was sent from my Wemos D1 Mini to my Telegram bot.

      Reply
  10. This is not a very practical project for the very reason that when Telegram finally decides to post the comments can be 15 minutes after the open or close event.

    Reply
  11. Hello!
    Is it possible to run this with 2 or more door switches ? If so, would be nice to explain or make an example of it!

    Greetings,
    Jozef

    Reply
  12. Ok so I had some fun with this as I am also just learning, hope this helps. What I did to see if it works was to follow the instructions to set up the circuit, I used a Wemos D1 and used a 4.7mfd cap in in parallel with the contacts. Basically I duplicated the instructions to add a second door to the circuit.
    I added 2 leds one for each door on my breadboard to see that the responded to the switch changes and they followed state changes. I also wrote comment the bot send message “the other door”.
    Things I added :
    const int for each led
    pinMode for each led
    pinMode for second switch
    const int for additional switch
    state for second door
    attached another digital interrupt
    added to if statements for second door
    also added digitalWrite for leds so I could see it happen easier
    Let me know if this helps or if you have a problem with the code.

    Reply
  13. Hello Sarah,

    I made two electronic circuits to detect door openings that I modified for two doors each. They both work perfectly on my internet box in my first house.
    I put one of the two circuits in my second house but with internet through a 4G router. The circuit immediately connects to the WIFI network, but no return to my telegram account.
    I created a second telegram token and correctly put it in the ARDUINO program, but still the same, no feedback on my new telegram account.
    What’s going on ?
    I think there must be a port opening problem on the router, but which one?
    I put a fixed address on the router for my electronic circuit, it automatically always connects to the same address, but no return to the telegram account.
    I opened port 443, but is it the correct port, because still no return on the telegram account?
    Do you have any idea what would be wrongly configured?
    Thank you very much for your response and suggestion.
    Jean Yves

    Reply
    • I have done this with ESP8266 12-f Di mini . All I did was look at serial monitor , copy up and all works. Trying to get 2 on one board is a challenge for me. Don’t really like this project because of the bounce on the reed switches , used caps and still see the multiple reads.

      Reply
  14. Hello Sarah,

    I made two electronic circuits to detect door openings that I modified for two doors each. They both work perfectly on my internet box in my first house.
    I put one of the two circuits in my second house but with internet through a 4G router. The circuit immediately connects to the WIFI network, but no return to my telegram account.
    I created a second telegram token and correctly put it in the ARDUINO program, but still the same, no feedback on my new telegram account.
    What’s going on ?
    I think there must be a port opening problem on the router, but which one?
    I put a fixed address on the router for my electronic circuit, it automatically always connects to the same address, but no return to the telegram account.
    I opened port 443, but is it the correct port, because still no feedback on the telegram account.
    I created a second token and I “copy and pasted” in the ARDUINO program, so no error and … no response on TELEGRAM.
    I use the same TELEGRAM account as for my first house, so the same identifier.
    Do you have any idea what would be wrongly configured?
    Thank you for your response and suggestion.
    Jean Yves

    Reply
  15. keep getting this error
    ESP8266_Telegram_Door:44:15: error: ‘TELEGRAM_CERTIFICATE_ROOT’ was not declared in this scope
    44 | X509List cert(TELEGRAM_CERTIFICATE_ROOT);
    | ^~~~~~~~~~~~~~~~~~~~~~~~~
    Multiple libraries were found for “UniversalTelegramBot.h”
    Used: /Users/1234/Documents/Arduino/libraries/UniversalTelegramBot
    Not used: /Users/1234/Documents/Arduino/libraries/Universal-Arduino-Telegram-Bot-master
    exit status 1
    ‘TELEGRAM_CERTIFICATE_ROOT’ was not declared in this scope

    Reply
    • ok….I needed to update the ESP8266 libraries and use the latest Telegram bot library… you can remove my comment.

      Reply
  16. hello. Looking for a way to alter the tutorial
    -https://randomnerdtutorials.com/esp8266-nodemcu-mqtt-publish-ds18b20-arduino/

    so that it will also publish to MQTT at the same time,but i am facing issues with the code.

    What i am trying to achieve is an ESP8266 with reed switch. So when there is an open door then it will publish a message to Telegram and to MQTT at the same time. is it possible to guide me with this code, please?

    Reply
  17. Creo que la ISR está mal gestionada por eso hay quejas de robotes.
    Cuanto se activa la ISR, esta rutina ha de quedar inhibida durante un periodo de 1.5s.
    El bucle principal, “loop” ha de mantener la ISR bloqueada para evitar que se modifique “changeState” durante este tiempo lo que provocaria resultados erráticos por rebotes mecánicos del relĂ© reed.
    Pasados 1.5s, se habilitará nuevamente la ISR para detectar nuevos cambios de estado y validar “changeState”.
    El relĂ© reed, solo se lee una vez en el “setup”, luego vamos alternando puerta abierta, puerta cerrada con los cambios. NO tendremos la seguridad de coincidir “state” con el estado de la puerta despues de muchas maniobras. Mejor asegurar la lectura del reed despues de detectar un cambio y salir de la temporizacion de 1’5 segundo.
    Saludos

    Reply
  18. hi,
    i loved your project. I tried it with a node mcu but in my case the bot sends “the door is open” and “the door is closed” messages for a long time even if i do nothing. am i missing something? tried it with a wemos d1 too but the result is same. after the bot started up it sends door open and close messages for few minutes. thank you.

    Reply
    • Hi.
      It might be an issue with your circuit or with the door sensor you’re using.
      You might need to add some debouncing code to prevent that.
      Regards,
      Sara

      Reply
    • I’ve had same issues, tried with several devices. Never really got it to work to my satisfaction but have had suggested to me to put a 22 mfd cap in parallel with door contact. Again, for me it wasn’t satisfactory but it may work for you.Good luck

      Reply
  19. Hello Sara, hello Rui,
    Thank you very much for posting those very detailed and helpful tutorials.
    Is there a code line I can add to get a timestamp (sent when the event happend) in the message?
    But without setting up a #include <NTPClient.h> ?

    BR,
    Sebastian

    Reply
  20. Hello Sara, hello Rui,
    Thank you very much for posting those very detailed and helpful tutorials.
    Is there a code line I can add to get a timestamp (sent when the event happend) in the message?
    But without setting up a #include <NTPClient.h> ?
    BR,
    Sebastian

    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.