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.
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.
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.
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.
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.
3) Search for “Webhooks” and select it.
4) Select the option “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.
6) Then, you need to click the Add button on the “Then that” menu to select what happens when the previous event is triggered.
7) Search for email and select the email option.
8) Click on Send me an email.
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.
10) Now, you can click on Continue.
11) Finally, click on Finish.
12) You’ll be redirected to a similar page—as shown below.
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.
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.
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.
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:
- ESP8266 – read Best ESP8266 Wi-Fi Development Boards
- 1× Magnetic Reed Switch
- 1× 10kΩ resistor
- 1× breadboard
- Jumper wires
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.
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");
}
}
}
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.
For prototyping/testing you can apply the magnetic reed switch to your door using Velcro.
Now when someone opens/closes your door you get notified via email.
Watch the video demonstration
We recorded this video several years ago (I’m sorry for the bad quality).
Wrapping Up
In this tutorial you’ve learned how to trigger an event when the reed switch changes state. This can be useful to detect if a door, window, or drawer was opened or closed. You’ve also learned how to use IFTTT to send an email when an event is triggered.
Instead of sending an email, you may want to send a message to Telegram, for example.
We hope you’ve found this tutorial useful. If you want to learn more about the ESP8266 board, check out our resources:
- Home Automation Using ESP8266
- Build Web Servers with ESP32 and ESP8266 eBook (2nd Edition)
- More ESP8266 Projects and Tutorials…
Thanks for reading.
Cool project!
Thank you!
Thank you Rui,
Great job, as always 😉
Thank you Roger!
Very good an easy,thanks for this cool project!!!And….keep on sending….please…
Thank you! I will send more soon
Good article, but I don’t see the sketch anywhere. It would be kewl to see it. Thanks.
Which browser are you using?
Can you try again? Or open this link: https://raw.githubusercontent.com/RuiSantosdotme/Random-Nerd-Tutorials/master/Projects/Door_Status_Monitor_using_the_ESP8266.ino
That worked Rui – Thanks Again 🙂
What kind of component beside 10kΩ resistor on mini breadboard?
Kweeelll project. I’m going to attempt this.
Can I convert to python language?
I’m using a Magnetic Reed Switch, I have a link to that sensor in this blog post in the “Parts Required” section.
You can read more about that sensor in this project example: https://randomnerdtutorials.com/monitor-your-door-using-magnetic-reed-switch-and-arduino/
Amazing project…Great work !
Thank you!
What about Energy consumption? I guess that code inside loop will drain the battery soon.
Shouldn’t be better to use the sleep function?
Thanks!
Hi Javier,
Power consumption wasn’t a concern in this project and I’m using the ESP8266 connected to a wall power supply.
But the sleep function might be a great enhancement to this project
Thanks!
This is great, Rui. I’ve been a fan since I first started tinkering 🙂 I was wondering if this works the same way as a bluetooth HC-05 module ? I have tried something similar but i ran it off my phone, the only problem was that had to be on 24×7. Does this module have a workaround where it turns the entire setup on and off based on PC messages ?
Hi Assad,
Thank you for your continuous support!
The HC-05 is a bluetooth module that it’s not connected to the internet. The ESP8266 is a WiFi module, so it’s actually connected to the Internet to send those emails.
This project is also running 24×7, but you can stop and restart the project whenever you feel like.
Rui
Olá,
great! I’m thinking to use this with a washing machine to get a notification of the end of the laundering, but I will get the info on the LED END notification for this i’m thinking use a photo-resistor, you now if I can simply change the reed switch by the photo resistor?
Necessary to change the code?
You need to use an Analog pin with your photoresistor to determine the value.
And the ESP-01 doesn’t offer that kind of pin.
Here’s more information on that subject: https://randomnerdtutorials.com/esp8266-adc-reading-analog-values-with-nodemcu/
Excellent, THANKS RUI !!
I will give it a go!
Thanks Rod! Let me know your results!
Thanks for another great tutorial Rui
Another great tutorial and successful project built, thanks Rui.
Thank you Geoff!
Hi can someone please clarify the following
const char* ssid = “YOUR_SSID”;
const char* password = “YOUR_PASSWORD”;
I know the SSID of my wifi modem as it comes up on the PC Task bar.
Is “YOUR_PASSWORD” the MODEM password or is it the “Network KEY”
When connecting a friend to my home network they search for the SSID and then enter the “Network KEY”. I assume its the network KEY I need here NOT the modem password. My problem is Ive tried both and neither work. So I have another problem but I need to get the password correct. Can anybody confirm this.
Hi,
The SSID is the name that you see in your computer as the network name.
And the password is the same password you need to enter in order to your router with any device…
How are you sure that your ESP isn’t connecting to your router?
What do you see in your Arduino IDE serial monitor at a baud rate of 115200?
Hi Rui
I found the problem I had the CPU set at 80 MHz.
The Arduino Serial Monitor output is ..
WiFi connected
IP address:
10.0.0.105
1
opened
connecting to maker.ifttt.com
Requesting URL: /trigger/door_status/with/key/c8O
0
closed
connecting to maker.ifttt.com
Requesting URL: /trigger/door_status/with/key/c8O
Looking good now.
Thanks
Olá Rui! Tenho acompanhado seus excelentes tutoriais;
Mas, gostaria de uma informação: Qual a diferença deste ESP8266 para o Módulo Bluetooth HC-06 ou 05?
Obrigado
This worked great with the “ESPDuino Development Board ESP13 UNO R3 With Wifi” from Banggood. This was also my first time using an IFTTT account. I really appreciate your time in posting this for all of us.
Hi Wayne,
Awesome! I’m glad it worked as expected. Thanks for sharing,
Rui
pinMode(pin, OUTPUT);
Please, is that correct ? GPIO_2 shouldn`t be and INPUT pin in order to catch the sensor status ? Thank you very much for your work.
Please ignore my previous question about pinMode(pin)… I`ve just read about attachInterrupt function. It`s clear now. Sorry and thanks again !
not sure what i am doing wrong when Test the url I get cogradulations but no email is sent or recieved
Did you change the default URL in the IFTTT recipe?
got it working it was my gmail not connecting. I have to say this is amazing and thank you. I am using it as a sump pump monitor with a little float switch to email me when water level gets too high (IE the sump pump failed). I am using a NodeMcu and the arduino ide works perfectly on it. what I am trying to figure out now is can it be modified to look at a second gpio for my second sump pump. then send a email as to which pump has failed. once again thank you .
alan
You’re welcome Alan! I’m happy to hear that it’s working as expected 🙂
Hola Buenas tardes
Ya me dirás por favor como has conseguido que tu proyecto envie emails, a mi no me funciona sin embargo si que me envia emails desde la página de IFTTT “documentación” haciendo clic en TEST y también introduciendo la Url completa con la clave correspondiente en el navegador. Pero cuando pongo en nivel bajo o alto el pin no me envia nada. En el monitor serial me indica bien la conexión y los cambios de estado, lo último que me dice es :
connecting to maker.ifttt.com
Requesting URL:/trigger/door_status/with/key/https://maker.ifttt.com/trigger/door_status/json/with/keyxxxxxxxxxxxxxxxxxxxxxxxxxx
Si me pudieras ayuda te lo agradecería
Un saludo
Hi.
Maybe there is an issue with IFTTT?
Make sure you’re using the right links to send the email.
You can check if something is wrong with the applet itself. Go to this link: https://ifttt.com/my_applets
Click on the bell icon on the applet your’re using to send emails, then click on “view activity”.
Maybe you’ll get more information about why you’re not receiving the emails.
Additionally, you may want to consider sending the emails using SMTP without using IFTT: https://randomnerdtutorials.com/esp32-send-email-smtp-server-arduino-ide/
Regards,
Sara
Got your message today, but does not matter, never too many projects using ESP8266.
Thanks a lot gonna try them soon.
Thanks for reading!
Rui
Hi
Thanks for the great project
Thanks!
Hi thanks for the great project
But I am using the esp-12 can you please tell me the codes and schematic for that on my gmail
You can download from this page
I’m using ESP8266-12e and finding it to be very unstable, sometimes it doesn’t boot well and I have to restart it, many times it completely pukes and dumps the stack. Is this normal for the 12e’s? I’ve worked with ESP8266-01’s and have not had this kind of instability. Any thoughts would be appreciated. Also, I can’t get the POST to work, it basically does nothing, but if I use GET code it works flawlessly. Does anyone have a sample of what the JSON POST should look like so I can make sure mine is right?
This can happen due to power issues…
Make sure you supply enough current to have a stable ESP8266 running.
Thanks,
Rui
Hi Rui,
Would be possible to have it showing up in DOMOTICZ? If yes, how would be the code? Could you help? 🙂 Tks and congrats for the project!
Sure, I’ve never used the Domoticz platform, but you simply send an HTTP request to the Domoticz platform
Thanks so much for this example and code.
I even added a few lines of code to make a beep (using a piezo) when the door opens and closes.
I’m glad I could help! Thanks for reading,
Rui
Great project! There is a problem I’ve found: if GPIO2 is low at boot time, the ESP-01 doesn’t boot, so you cannot boot the ESP while the door is open.
Hi,
is it possible to see the status of the door with no concern of getting a mail ?
i want to monitor if a door is open after 4 pm in a school classroom and don’t care to see all the mails if it was open or closed during the day
thanks
ben
Yes, instead of triggering the email action every time the door closes, you can add an RTC to the ESP8266 (or check the time online).
Then, it only trigger the email action if it’s after 4PM
Great project. I looking for it.
Can you advise how to do it with Sonoff(smart Wi-Fi switch 10A) Thank you!
Thanks for the suggestion.
Right now I only have these tutorials related to the Sonoff: https://randomnerdtutorials.com/category/sonoff/
I have the Sonoff. I want to do the Door project. How should I wiring and what (GPIO) need to change in the code? Thank you for support.
Thanks. Please advise.
1.I sould change in sketch to int pin = 0 (for getting email from button) or int pin = 14(for getting email from door sensor) ;
2. upload you sketch to Sonoff.
Is it correct?
I did it with Sonoff. I have one question. If I open and close the door fast I didn’t get two emails. only one. After it emails are not correct.
Hi Rui,
Sorry. It’s not so good. Rui, can you change the sketch. I’d like to know status the reed switch exactly -close or open. Thank you.
close
Rui,
How to know close: contact or open?
Simply read the current state of the reed switch
No, for me it’s difficult. You did the good project and posted it in detail. I’ve repeated it only. Would you like to change the sketch with “read the current state of the reed switch”?
And GPIO for led (door state) (I use sonoff)
Thank you.
I am stuck. i have completed testing of maker app with my key , did the firmware flash -nodemcu firmware programmer, loaded sketch with my credentials (SSID,password,key). Connected the circuit as shown by you, but still cannt get the esp to trigger/send a msg to my gmail acc. i thing i did notice, after loading sketch, i tried sending AT commands through serial monitor, not getting an response back. Not sure were i went wrong. ( i am using 2 AA to power up my project)
When you open the IFTTT URL in your browser, do your receive an email?
yes, i can set a trigger through ifttt and receive a msg but with esp chip, it doesnt do anything. Connections are done as per your given circuit, but still it doesnt trigger. I can load the sketch through Ardunio on to esp chip , but later when connected to reed circuit, it powers up, but doesnt do anything. Also as mentioned earlier, i am not able to test the AT commands on the esp chip. is it normal ?
pls reply/help …
Hello Rui,
Congratulations with this project. I buy all the parts and replicate your project:)
Everything is working good. But I buy the wrong switch, when I open the door
I get the message “door closed” and the message “door open” when closed.
Do I need to buy a other switch or can I alter something in the code?
Rui, one more question: Can you alter the code, so I can use the same
principle for my mailbox with a Microswitch instead? To receive only one
message when the postman open the hatch. And maybe implement “Pushover”
beside gmail. Very exciting!
Kind regards,
Thanks for reading,
Try switch the logic in my code to use give you the messages in reverse. I can’t create custom projects at the moment due to time constraints..
Thanks,
Rui
It looks like GPIO2 will be low if the door is open during boot. Can you confirm? I might suggest to set serial to TX only and use GPIO3 (ESP RX) for the reed switch.
Nick, I have the same issue. Please read my previous comments.
Try close and open one time fast. After it will be correct email. I can’t fix the sketch. We need “Simply read the current state of the reed switch”
Now it changes email any time when was event and not depend on the state of the reed switch.
Hello thanks for your post.
I think is better to do work this project on battery ans use interupt To wake up esp8266 i see the esp8266 work with only few micro-amp.
Sorry for my english i’m french.
Exactly, that’s the best solution
Regards,
Rui
what is name this circuit
This circuit was created using Fritzing
Can u plz check it once
#include
#include
#include
#include
#define USE_SERIAL Serial
#define trigPin 9
#define echoPin 10
#define piezoPin 8
ESP8266WiFiMulti WiFiMulti;
int normalDistance;
boolean triggered = false;
long duration, distance;
void setup() {
USE_SERIAL.begin(115200);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(piezoPin, OUTPUT);
long duration, distance;
while (millis() 0; t–) {
USE_SERIAL.printf(“[SETUP] WAIT %d…\n”, t);
USE_SERIAL.flush();
delay(1000);
}
WiFiMulti.addAP(“hema”, “hema9966”);
}
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration*0.034/2;
USE_SERIAL.print(“Distance: “);
USE_SERIAL.println(distance);
if (distance 0) {
// HTTP header has been send and Server response header has been handled
USE_SERIAL.printf(“[HTTP] GET… code: %d\n”, httpCode);
// file found at server
if(httpCode == HTTP_CODE_OK) {
String payload = http.getString();
USE_SERIAL.println(payload);
}
} else {
USE_SERIAL.printf(“[HTTP] GET… failed, error: %s\n”, http.errorToString(httpCode).c_str());
}
http.end();
}
}
}
ultrasonic and buzzer are working in (Tools <board<Arduino/Generic uno)
and wifi module is working in onlt(Tools <board<(any esp8266 in down column)
when i mix ultrasonic and buzzer nothing happening)
any idea
thanks
Has anyone tried this project using the Witty board? I’ve built it using the board shown, and it works, but would like to expand it using a Witty to send light levels.
I’ve never used that board before Andrew.
Thanks for asking,
Rui
awsome with some -01 projects.
would it require a lot if the unit should go deepsleep and awake on the magnets seperating? then send the IFTTT and go back to sleep again?
Hi Rui. In your code you have the pinmode for “pin” as OUTPUT. Shouldn’t it be INPUT?
Great tutorial, thank you. Is it possible to connect more then one ESP8266 to applet so I can monitor all my doors in my house. Do I need to change door_status but use the same key?
You could use the same applet and the same API key in all your devices.
In your post request you could pass a value that would indicate in the value which ESP posted that event…
Looks like a fun project. I am really new to this type of connection to the web so I am not too knowledgeable on some of the details. On the final schematic I do not see a power source. What voltage is required and how it it connected?
The ESP-01 uses 3.3V
Good morning: Thanks for your project. When I replace the password in the web address it says “Congratulations! You’ve fired the door_status event” but I do not receive the email. I do not know how to do it to receive it.
Hi Braian.
Did you test your IFTTT applet before uploading the code?
If you’re not receiving an email, it may be a problem with your applet.
Exactly, until I get the text “” Congratulations! You’ve fired the door_status event “but I never receive the email in gmail. Please do not know how to continue
Hi again.
In your IFTTT account, go to “Activity” in the following link: ifttt.com/activity
Make sure your applet is turned on. Also, in the “Activity” section, you can see if something is wrong with that specific applet.
It may tell you why it is not sending the email.
I hope this helps.
i am using this 8266 board.
http://www.instructables.com/id/Getting-Started-With-ESP8266LiLon-NodeMCU-V3Flashi/
Can you tell me which gpio you are using?
Hi. We’re using esp8266-01, and we are using GPIO2.
If you want to use that esp8266, you need to use GPIO2(pin marked with D4).
I hope this helps.
Regards,
Sara 🙂
This is great. Can you use deepsleep on this for those running off batteries? Also use mqtt instead of email? I have the ESP8266–01
Yes, you should be able to do everything that you’ve said. This project should run on batteries and can easily make MQTT publish messages.
for me it’s not working,
it is triggering the url from ESP, but when i trigger the url from the browser, it’s working for me.
Please help me.
Make sure you’ve added to the course the exact URL as I illustrate and double-check your SSID/password.
Hi, am not getting any email as notifications, but testing result getting ok
Hi.
You need to provide more information about your problem, so that we can help.
Regards,
Sara
Hi Rui,
Why, am not getting enough mail notifications of this project, when am testing by URL, it shows congratulations ,n fire it but mail not receiving.
Pl send me reply by my mail
Thank you,
The test url is HTTPS:// but the ESP8266 code says it is using port 80 http:// I am not sure where to change this in the code.
IFTTT supports both HTTP and HTTPS requests, so it should work with HTTP…
Regards,
Rui
Sorry but the Ifttt directions are no longer working.
Sorry I am a dumb guy, figured out the mail problem
Hi.
That’s ok!
I’m glad it is now working!
Regards,
Sara 🙂
Hi Rui Santos,
Dear I m getting error, when event is triggered from my laptop & the email is not sent to my mail box at given email address. Web browser message ” Congratulations! You’ve fired the door_status event ” is OK.
In activity window I get Action Skipped Error.
Action skipped after 5 action errors.
Please help me to resolve this problem.
Thanks & kind regards,
Yawar Saeed
Hi Yawar.
I think it may be some problem related with IFTTT services. I’ve never faced that error.
Can you take a look at the IFTTT error glossary and see if it helps?
https://help.ifttt.com/hc/en-us/articles/115004914234-Activity-feed-error-glossary-
Regards,
Sara 🙂
why I cannot get the email? I have put my nodemcu ssid or my ssid home wifi? I dont understand,, sorry I still new in this
Hi.
Did you test the applet? Did it worked well?
Don’t forget that you need to insert your own API key on the following line:
const char* apiKey = “YOUR_IFTTT_API_KEY”;
Regards,
Sara 🙂
Great tutorial, thank you!!!,
what kind of component is that near the resistor on the breadboard?
Best Regards
Hi Simone.
It is a magnetic reed switch.
https://makeradvisor.com/tools/magnetic-reed-switch/
Hi Sara,
thanks for your replay! 😉
Why is was used a 10kΩ resistor?
Is it fundamental?
Best Regards,
Simone
Hi.
The reed switch works like a pushbutton. So, it is advisable to use a 10k resistor to prevent false positives.
It is advisable, but not mandatory. However, you may have an unexpected behavior without the resistor.
Regards,
Sara 🙂
I have similar setup using esp-8266-12 setup to email me using IFTTT when garage door changes from open to close or close to open. What I would like is can one esp-8266 communicate to another esp-8266 over my home wifi? They are too far apart to communicate directly. I want the second esp-8266 to then send hardwired signal to my home security system on the garage door status. Thanks.
Hi Paul.
They can communicate using your home Wi-Fi if both boards have access to the same Wi-Fi network.
Hey Sara and Rui!
Thanks for this very easy tutorial! Its my first project with an ESP-01 at all and I got the ESP programmed in unter 2h, inc. communication to the serial monitor stating the connection to Wifi and the triggering of the IO (just connecting it to 3.3V).
Also triggering the IFTTT applet to send a mail to my inbox works via my browser!
But doing it via the ESP does not work. Is there any configuration neccessary on my router to allow the ESP going through?
KR
Maik
Hi Maik.
Thank you for reaching out.
The only thing you need to do is to include your network connections (SSID and password) on the code and insert your own unique API key on the code.
We haven’t done any other configurations.
Are you getting any errors on the serial monitor?
In your IFTTT account, you can go to “Activity” to see if the IFTTT is receiving your request.
Regards,
Sara
This is really useful. I’m stuck with IFTTT – I get the website confirmation but no emails to me gmail account. Any suggestions?
Hi Brian.
Are you using a Gmail account?
Using the Documentation tab in Webhooks I am able to sen a test email to my gmail account using door_status in the event box. Just not working from the esp8266. The serial monitor reports opening, closing and connection to ifttt.com.
It does NOT send any e_mail. The activity says : applet skippedbecause the url must begin with HTTP….
Any help to solve the problem please ?
Thanks
Ambro
Hi.
replace this line on the code
const char* host = “maker.ifttt.com”;
with
const char* host = “http://maker.ifttt.com”;
I haven’t tested it, but it should solve the problem.
Let me know if it works.
Regards,
Sara
Hi, great tutorial! Please can you tell me why are you using resistor? Can it be done without resistor? And can it be done with Wemos D1 mini instead of esp8266? 🙂 Thanks!
Hi Timothy.
Yes, you can use a wemos d1 mini instead.
You can use the circuit without resistor, however, you’ll be more likely to have false positives.
Regards,
Sara
Hi
I trying this on my wemos d1 mini, not getting there quite yet 🙂 I just wonder where to add my magnetic reed switch?
What/where is int pin = 2; for reed switch? I got the notification in my web browser (pc) but no mail either pc or phone.
Which magnetic reed to use, NO or NC?
Hi.
You need to connect the reed switch to GPIO 2 (marked D4) on the board. Check the Wemos pinout here: https://randomnerdtutorials.com/wp-content/uploads/2015/01/esp8266-wemos-d1-mini-pinout-1024×677.png
We’re using normally open reed switch. (but you can use either one, just need to change the logic on the code)
Regards,
Sara
Hi
Thanks for answering😁 got it going now but the e-mail does not work. It works in browser but I dont get any mail. My e-mail is correct in ifttt. Please hjelp 😁
Hi
I guess this is why : “Triggers for the Gmail service are inactive”
status.ifttt.com/incidents/0pb2pp4l3bx1
Frode
Hi,
Confirmed – IFTTT has disabled the trigger for Gmail.
Gmail actions may fail for some users
Identified – The issue has been identified and a fix is being worked on. It will require a large rework in how Gmail is implemented, we appreciate your patience as we get Gmail up and running for everyone.
May 15, 16:51 PDT
Hi.
It seems that the Gmail option is temporarily not working. I’ve tested and it is not working for me either. There is a problem with the gmail services on IFTTT at the moment.
However, there is an alternative.
When you’re creating a new applet, after clicking the “that” word. Instead of searching for gmail, search for “email” and select the “email” option.
Then select the “Send me an email” option. Proceed as described in the tutorial then. That worked for me a few days ago.
Thanks.
Regards,
Sara
Good day,
I am struggling to get notifications from this event. Is there a workaround to get notifications to a gmail account?
I tried your alternative suggestion, but without success.
Thank you for great projects!
Kind regards
Louis
Hello Louis, instead of using the gmail account, search for the “Email” service on IFTTT. It works exactly the same.
I hope that helps!
Regards,
Rui
would it be possible to hook up multiple magnetic reed switches to a single esp8266 in order to monitor multiple doors from a single esp8266? if possible, would the wire length be an issue?
Hi Tim.
If you’re using an ESP-01, I don’t think you’ll be able to attach many reed switches.
If you’re using another ESP8266 like the NodeMCU Kit, you should be able to attach more reed switches.
As for the wire length, it can be an issue, but you have to experiment yourself and see the results.
Regards,
Sara
Sara,
thanks for the quick reply! yeah, i was talking about an ESP-01, but i think i have others that might fill the bill. i’ll tinker a bit and see what i can come up with.
thanks again!
-=tim
Hi both, haveyou come across the ‘ISR not in IRAM’ error message with the esp01? I’ve Googled it and It seems to be something to do with the interrupt. I only get the error when uploading the door status monitor code, other projects such as the wifi button work fine. Any suggestions???
Hi Neil.
Add ICACHE_RAM_ATTR before void changeDoorStatus() {
like:
ICACHE_RAM_ATTR void changeDoorStatus() {
This should solve the problem.
We’ll update the code.
Regards,
Sara
Fantastic! thank you….
Hello, fantastic tutorial.
My question, is it possible using esp32 and ESP32_MailClient.h?
Thank you.
Hi.
Yes.
You can see this example: https://randomnerdtutorials.com/esp32-send-email-smtp-server-arduino-ide/
Regards,
Sara
Hi, i hope health is ok.
I have been working with that code that you indicate, but I am not able to include it in the code of the magnetic sensor, I always have an error.
can you give me some indication?
greetings from Spain.
Hi Julio.
What error do you get?
Regards,
Sara
Hi Sara,
I have problems with ifttt, and I do not receive email from esp8632, my thought is to do it with esp32 and ESP32_MailClient.h, it works very very well and without third party problems, but I don’t know how to add the magnetic sensor, I am very very newbie, a help? 🙁
I feel my bad language.
greeting. 😉
Hello,
I have don this project and it work perfect for years, BUT, why is neewnded to be always an BUT?
The problem is that IFTT does not allow anymore to enable webhooks at this project, it give some error when you want to enable this project. So if you have this project done and working, and you will disable it and want to reenable it in IFTTT, will now work anymore and i do now know why, maybe you can help me to find out why…
hello, can anyone tell me where is the problem with this project? any news? why ifttt doesnt allow to work anymore?
any news? doesnt work anymore, can you fix it?
Hi Dan.
I think it has some problem with the Google Services.
When creating an applet, instead of the gmail option, choose the “mail” option.
Regards,
Sara
hello,
cannot find that option, can you guide me?
and what is the use of the IFTT? cant you make it to send e-mail without iftt? please, i realy need it
How can I get email notices without having to rely on IFTTT?
That is what I want also. I don’t want to rely on IFTTT. How can I send an email directly from my ESP8266 / wemos D1?
Hi.
We have this project that you can follow: https://randomnerdtutorials.com/esp32-esp8266-send-email-notification/
Regards,
Sara
hi, i was wondering what power the circuit took?
Hi.
You just need to power the ESP-01 using a 3.3V power source.
Regards,
Sara
thank you for your help.
Hello
This project is interesting BUT DO YOU HAVE a version where we can use a standard ESP12E card ?.
Best regards
Hacine
Hi.
You can use this project with other ESP8266 boards.
Just make sure you wire the reed switch to GPIO 2. You can also use other GPIO, but don’t forget to change that in the code.
Regards,
Sara
I had this working no problem a couple of years ago. I’ve wasted a lot of time trying to get it to work again only to discover IN THE COMMENTS that there is a problem with GMail.
Please put a warning at the top of the page so other people don’t waste their time.
Also the link https://ifttt.com/applets/388514p-send-email-with-the-esp8266 doesn’t work anymore.
Please update this project.
Hi.
Thanks for pointing that out.
I’ll update this project soon.
Regards,
Sara
Hi Rui and Sarah. This works very well. Can this also be made for Telegram? I only have the detection of that and it shows 1 status. Door (or something like that) open or closed would be nice. thanks
Hi.
Yes.
We have a similar version of this post using Telegram.
It will be published in a few weeks.
Meanwhile, you can try to adapt this project by following the Telegram tutorials:
– https://randomnerdtutorials.com/telegram-esp8266-nodemcu-motion-detection-arduino/
Regards,
Sara
IFTTT isn’ t free anymore.
You can use up to three free applets.
I have tried with GMAIL and YAHOO and no one works.
Could it be because ifttt is on https and we need some digital certification???
Hi.
when you say it didn’t work, what happen exactly?
Did you check on the IFTTT dashboard if the event was triggered?
Regards,
Sara
Hi
Nice tutorial, but I doesn’t manage to get any response in IFTTT that it getting my request.
Regarding to serial.. it all seems fine, connecting to wi-fi and sending the link.
The IFTTT link by itself work fine.
Can’t figure out what I’m doing wrong. What do you need from me to be able to assist, if you have the time:)
Hi
Check if you copied the IFTTT API key correctly and that you’ve created the applet exactly as shown in the tutorial.
Regards,
Sara
Hi,
I’ve recently revisited this tutorial to adapt it to use a reed switch to capture gas meter pulses and report to Home Assistant via MQTT. I developed it initially using a push button and all works as expected, but I notice that when I use the reed switch, I get multiple state changes on the transition from ‘closed’ back to ‘open’ (reed switch is NC type, so this is when reed switch is closing again). See terminal extract below. first two transitions are using push button switch, second two are using reed switch.
14:10:27.951 -> State changed
14:10:27.951 -> 1
14:10:27.951 -> closed
14:10:29.275 -> State changed
14:10:29.275 -> 0
14:10:29.275 -> open
14:10:33.687 -> State changed
14:10:33.687 -> 1
14:10:33.687 -> closed
14:10:35.964 -> State changed
14:10:35.964 -> State changed
14:10:35.964 -> State changed
14:10:35.964 -> State changed
14:10:35.998 -> State changed
14:10:35.998 -> State changed
14:10:35.998 -> State changed
14:10:35.998 -> State changed
14:10:35.998 -> State changed
14:10:35.998 -> State changed
14:10:35.998 -> State changed
14:10:35.998 -> 0
14:10:35.998 -> open
I’m curious as why this happens – is is just bouncing of the reed contacts as they close again? The strange thing is that it is always 11x state changes before the result (after the debounce time) is reported. Changing the debounce delay makes no difference to the number of state changes logged.
Any ideas what could be going on here?
Regards,
Peter
Always 11 changes is a clue for sure. Bouncing is not that regular. You also only get one report of “0” and “open”. There must be something else in the code driving the behavior…but only you can see that!
You might want to post it.
Dave
I have follow all steps as given above successfully. but i am facing problem with this project i haven’t receive email from IFTTT when I disconnect magnetic sensor.
HI RUI;
I don not know why I am not getting emails sent to my gmail?I am using an IPHONE- not sure if it matters.
There is a website to check the TEST and it show it working but I am not getting any emails (gmails) on my iPhone .
I read a comment a person with gmail had a problem but he got it working. He asked for another way to send it to his website. Replied from Sara sent him another website that will allow him to directly send email without the IFTTT-
https://randomnerdtutorials.com/esp32-esp8266-send-email-notification/
I will try it!
I appreciate if you can answer my question.
I enjoy your book.
Mike
Hi.
It is not related to the iPhone.
Did you check your spam folder?
Maybe there is an issue with IFTTT?
Make sure you’re using the right links to send the email.
You can check if something is wrong with the applet itself. Go to this link: https://ifttt.com/my_applets
Click on the bell icon on the applet your’re using to send emails, then click on “view activity”.
Maybe you’ll get more information about why you’re not receiving the emails.
Regards,
Sara
Hello,
it seems the Sketch is working correctly for me as I can see in the Serial Monitor. However I don´t receive emails by IFTTT. If I test the webhook manually it works.
Do I have to change the “Content-Length: 13\r\n\r\n” + since I changed the Event name?
BR
Matthias
Hola buenas tardes , felicidades por todos vuestro proyectos
He vuelto a retomar otra vez este proyecto “estado de puerta” el cual me interesa mucho y te agradecería me aclararas varios puntos.
Lo he hecho primero con el NodeMcu (Esp8266) y algunas veces envia emails a través de IFTTT y otra veces no.
No entiendo porque en el código está configurado el pin gpio5 como PULL_UP sin embargo en el dibujo hay colocada una resistencia en modo PULLDOWN, además si se programa en el código PULL_UP o PULL_DOWN creo que sobran las resistencias físicas.
También lo he realizado con el Esp8266-01 tal cómo se ve en el vídeo copiando el código desde el video y me pasa lo mismo algunas veces manda los email y otras veces no. También observo que el código le falta la parte de “Setup” y lo he tenido que añadir yo, también en el esquema pregunto que sentido tiene que al pin gpio0 vaya a positivo 3,3 V. y también la resistencia en modo PULL_DOWN
Agradecería me aclararas todos estos puntos y me dijeras si algo estoy haciendo mal
Muchas gracias
Un saludo
Hola buenas tardes , felicidades por todos vuestros proyectos me gusta como lo explicais pero tengo algunas dudas con el proyecto “door_status” y espero que me las aclararais.
He hecho el proyecto primero con el NodeMcu (Esp8266) y algunas veces a través de IFTTT envia emails o notificaciones y otras veces no.
He probado con IFTTT desde “documentación” haciendo el correspondiente “TEXT” y envia correctamente los emails o las notificaciones
Una duda que tengo porque en el código está configurado el pin gpio5 como “PULL_UP” sin embargo en el dibujo hay colocada una resistencia en modo PULLDOWN, además si se programa la entrada en el código PULL_UP creo que sobra las resistencia física.
También lo he realizado con el Esp8266-01 copiando el código desde el vídeo el cual es diferente al que presentaÍs con el NodeMcu y me pasa lo mismo algunas veces manda los email y otras veces no. También observo que el código le falta la parte de “Setup” y lo he tenido que agregar yo, también en el esquema pregunto que sentido tiene que al pin gpio0 vaya a positivo 3,3 V. y también la resistencia en modo PULL_DOWN
Agradecería me dijerais donde puedo descargar el código que presentais en el video de demostración con el Esp8266-01 pués parece ser que no es el mismo que presentais con el NodeMcu.
Os pido porfavor me aclarareis todos estos puntos o me dijerais que es lo que estoy haciendo mal pués me interesa mucho este proyecto.
Muchas gracias
Un saludo