Get a phone alert when a door opens

Use the IR obstacle sensor as a door sensor: the ESP32 counts openings, logs the time in Blynk and sends a notification while you're away.
  • Level:Advanced
  • Duration: 55 min
  • Ages 13+
  • Platform: ESP32

Tools for this lesson

Helpful for this build. Open a tool to see tips and more projects that use it.

Get a phone alert when a door opens – EEMENTOR STEM™ lesson

Did someone open your room, the fridge or the cookie cupboard? In this lesson the IR obstacle sensor watches a door from up close. When the door is shut, the sensor sees it; when the door opens, it doesn't. The ESP32 counts every opening, shows the time of the last one in the Blynk app and, when you switch on Guard mode, sends a notification to your phone.

What you'll learn

  • How an infrared obstacle sensor can work as a door sensor
  • How to filter out short flickers so one opening counts once
  • How to count events and reset the count every day
  • How to combine a switch in the app with a sensor rule

What you need

  • ESP32 board, expansion board and USB cable (ESP32 IoT Starter Kit)
  • IR obstacle avoidance sensor module (45-in-1 Sensor Kit)
  • Tape to fix the sensor to the door frame
  • A free Blynk account and the Blynk IoT app on a phone
  • A 2.4 GHz Wi-Fi network
  • Breadboard and jumper wires (ESP32 IoT Starter Kit)

Wiring

Breadboard wiring diagram: Get a phone alert when a door opens
Breadboard view. Check each connection against the wiring table below.
From To
IR sensor GND GND
IR sensor + 3V3
IR sensor OUT ESP32 GPIO 27
IR sensor EN Not connected

Sensor modules from different makers can label and order their pins differently. Always follow the labels printed on your module.

Fix the sensor to the door frame, facing the edge of the door, about 1 to 3 cm away when the door is shut. Turn the small screw on the module until its LED lights when the door is shut and goes out when it opens a few centimetres.

Set up Blynk

In the Blynk console, create a new template called Door alert (hardware ESP32, connection type Wi-Fi) and add these datastreams. Lesson 1 of this path shows each step in detail.

Virtual pin Name Data type Range Phone widget
V0 Door open Integer 0 – 1 LED
V1 Guard mode Integer 0 – 1 Button (switch mode)
V2 Openings today Integer 0 – 999 Value Display
V3 Last opened String n/a Value Display

Then open the template's Events & Notifications tab, add an event with the code door_open (name: Door opened) and turn on push notifications for it. The event code must match the sketch exactly.

Save the template, create a new device from it and copy its three BLYNK_… lines. In the phone app, open the device, tap the wrench icon and add an LED (V0), a Button in switch mode (V1) and two Value Displays (V2 and V3). Link each widget to its datastream.

Example screen for: Get a phone alert when a door opens
Example screen with sample values. Yours may look different.

The sketch

Replace the three BLYNK_… lines at the top with the ones from your device's Device info page, and add your Wi-Fi name and password (2.4 GHz only). The BLYNK_… lines must stay above #include <BlynkSimpleEsp32.h>.

#define BLYNK_TEMPLATE_ID "YOUR_TEMPLATE_ID"
#define BLYNK_TEMPLATE_NAME "Door alert"
#define BLYNK_AUTH_TOKEN "YOUR_AUTH_TOKEN"
#define BLYNK_PRINT Serial          // show connection messages in the Serial Monitor

#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include <time.h>

char ssid[] = "YOUR_WIFI_NAME";
char pass[] = "YOUR_WIFI_PASSWORD";
const char* TIME_ZONE = "EET-2EEST,M3.5.0/3,M10.5.0/4";  // Estonia; change for your country

const int SENSOR_PIN = 27;

BlynkTimer timer;
bool guard = false;
bool doorOpen = false;
int closedReading = LOW;         // the sensor's reading with the door shut
int openings = 0;
int today = -1;
unsigned long changedSince = 0;

String timeNow() {
  struct tm t;
  if (!getLocalTime(&t, 10)) return "time not set yet";
  char text[20];
  strftime(text, sizeof(text), "%d.%m %H:%M", &t);
  return String(text);
}

BLYNK_WRITE(V1) { guard = param.asInt(); }

BLYNK_CONNECTED() {
  Blynk.syncVirtual(V1);
  Blynk.virtualWrite(V0, doorOpen);
  Blynk.virtualWrite(V2, openings);
}

void checkDoor() {
  bool openNow = digitalRead(SENSOR_PIN) != closedReading;

  // The new state must last 300 ms before it counts
  if (openNow == doorOpen) {
    changedSince = millis();
    return;
  }
  if (millis() - changedSince < 300) return;

  doorOpen = openNow;
  Blynk.virtualWrite(V0, doorOpen);
  if (!doorOpen) return;                 // the door has just closed

  struct tm t;
  if (getLocalTime(&t, 10) && t.tm_yday != today) {
    today = t.tm_yday;                   // a new day: start counting again
    openings = 0;
  }
  openings++;
  Blynk.virtualWrite(V2, openings);
  Blynk.virtualWrite(V3, timeNow());
  if (guard) Blynk.logEvent("door_open", "Door opened at " + timeNow());
}

void setup() {
  Serial.begin(115200);
  pinMode(SENSOR_PIN, INPUT);
  delay(500);
  closedReading = digitalRead(SENSOR_PIN);   // the door must be shut at start-up
  Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);
  configTzTime(TIME_ZONE, "pool.ntp.org");
  timer.setInterval(50L, checkDoor);         // 20 times per second
}

void loop() {
  Blynk.run();
  timer.run();
}

Shut the door before you power up the ESP32: the sketch learns what "shut" looks like at start-up.

How it works

The module sends out invisible infrared light and has a receiver next to it. If something is close, the light bounces back and the output changes. With the door shut, the door edge is right in front of the sensor; with the door open, the light goes into the room and nothing comes back. Because modules differ in whether they output HIGH or LOW for "something there", the sketch stores the reading with the door shut and treats any change as "open".

Doors bounce and people pass close to the frame, so a reading must stay the same for 300 ms before it counts. Every 50 ms, checkDoor() compares the reading with the current state and restarts a small timer while they agree. Only a change that lasts beats the timer. An opening is counted once, at the moment the door opens, and the count starts again when the internet time says it's a new day.

Try this next

  • Send a notification when the door has been open for more than two minutes (for a fridge).
  • Add the active buzzer as a chime that beeps when the door opens.
  • Switch Guard mode on and off automatically at fixed times of day.

Troubleshooting

  • The device shows "Offline" in the app: check the Serial Monitor at 115200 baud. "Invalid auth token" means the BLYNK_AUTH_TOKEN line is wrong; if it never connects, check the Wi-Fi name and password, and that your network is 2.4 GHz.
  • Every opening counts as two: the sensor flickers at the edge of its range. Move it a little closer to the door, or raise 300 to 600.
  • Nothing happens when the door opens: turn the screw on the module so its LED goes out when the door opens.
  • It thinks the door is open when it's shut: the door was open at start-up. Shut it and restart the ESP32.
  • Openings today shows the count from yesterday: the ESP32 hasn't got the internet time yet. It resets after the first opening once the time is known.

Build it yourself

Everything used in this lesson comes in one kit, with parts tested by our engineers.

ESP32 IoT Starter Kit | Arduino IDE Compatible | Free Tutorials $57.00

Shop the kit