When the PIR sensor detects someone entering, the ESP32 immediately sends a message to your phone through Telegram. No server of your own and no router port forwarding: the ESP32 only needs an outbound Internet connection. What matters in this project is the detail that otherwise causes false alarms or hundreds of spam messages: the PIR warm-up time, a cooldown between alerts, and automatic WiFi reconnection.
Parts
- ESP32 DevKit board
- HC-SR501 PIR motion sensor (or the smaller 3.3 V AM312)
- Jumper wires and a 5 V / 1 A USB supply
- A phone with Telegram installed
How a PIR sensor works
A PIR (Passive Infrared) sensor emits nothing. It senses changes in infrared radiation when a warm body (a person, a pet) moves across its field of view. The OUT pin goes high on motion and stays high for a hold time before dropping, so one pass can produce a high level lasting from a few seconds to tens of seconds.
- Warm-up: after power-up the HC-SR501 needs about 30–60 seconds to settle, and OUT may go high at random. The code below ignores the sensor for the first 60 seconds.
- Two trimmers on the module: one sets sensitivity (range, 3–7 m), the other sets the hold time (about 3 seconds to several minutes). Turn the hold time to its minimum so your code controls repeat alerts.
- Mode jumper: position "H" (retrigger) keeps OUT high while motion continues; "L" gives a single pulse. Use "H".
- Voltage: the HC-SR501 is powered from 5 V (the ESP32 VIN pin), but its OUT signal is only about 3.3 V, so it can connect directly to an ESP32 GPIO.
Wiring
Creating the Telegram bot
- In Telegram, find @BotFather, send
/newbot, then choose a name and a username ending inbot. BotFather returns a token like123456789:AA.... It controls your bot, so never publish it. - Open your new bot and press Start (a bot can only message people who have started a conversation).
- Get your chat ID: message @myidbot with
/getid. The number it returns is your CHAT_ID (group chats have negative IDs).
Code
Install UniversalTelegramBot (by Brian Lough) and ArduinoJson (version 6 or 7) from the Library Manager.
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
const char* WIFI_SSID = "your_wifi";
const char* WIFI_PASS = "your_password";
const char* BOT_TOKEN = "123456789:AAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
const char* CHAT_ID = "123456789";
const int PIR_PIN = 27;
const uint32_t WARMUP_MS = 60UL * 1000; // PIR needs to settle after power-up
const uint32_t COOLDOWN_MS = 60UL * 1000; // at least 60 s between two alerts
WiFiClientSecure client;
UniversalTelegramBot bot(BOT_TOKEN, client);
bool armed = true; // toggled by Telegram commands
bool lastPir = false;
uint32_t lastAlert = 0;
uint32_t lastPoll = 0;
bool everAlerted = false;
void connectWiFi() {
if (WiFi.status() == WL_CONNECTED) return;
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
uint32_t t0 = millis();
while (WiFi.status() != WL_CONNECTED && millis() - t0 < 15000) delay(300);
}
void handleCommands() {
int n = bot.getUpdates(bot.last_message_received + 1);
while (n) {
for (int i = 0; i < n; i++) {
String chat = bot.messages[i].chat_id;
String text = bot.messages[i].text;
if (chat != CHAT_ID) continue; // ignore strangers who message the bot
if (text == "/arm") { armed = true; bot.sendMessage(chat, "Alarm ARMED", ""); }
else if (text == "/disarm") { armed = false; bot.sendMessage(chat, "Alarm DISARMED", ""); }
else if (text == "/status")
bot.sendMessage(chat, String("Alarm: ") + (armed ? "ARMED" : "DISARMED") +
", WiFi " + WiFi.RSSI() + " dBm", "");
}
n = bot.getUpdates(bot.last_message_received + 1);
}
}
void setup() {
Serial.begin(115200);
pinMode(PIR_PIN, INPUT);
connectWiFi();
client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // authenticate api.telegram.org
bot.sendMessage(CHAT_ID, "ESP32 started, PIR warming up for 60 s", "");
}
void loop() {
connectWiFi(); // reconnect if the network drops
bool pir = digitalRead(PIR_PIN);
bool risingEdge = pir && !lastPir; // only act when OUT just went high
lastPir = pir;
if (risingEdge && armed && millis() > WARMUP_MS &&
(!everAlerted || millis() - lastAlert >= COOLDOWN_MS) &&
WiFi.status() == WL_CONNECTED) {
if (bot.sendMessage(CHAT_ID, "Motion detected!", "")) {
lastAlert = millis();
everAlerted = true;
}
}
if (millis() - lastPoll >= 3000) { // polling commands every 3 s is enough
lastPoll = millis();
if (WiFi.status() == WL_CONNECTED) handleCommands();
}
delay(20);
}
How it works: a message is sent only when OUT just rose from low to high (rising edge), not continuously while OUT stays high. After each successful send the device stays quiet for 60 seconds. The commands /arm, /disarm and /status let you disable the alarm while you are home. Only your chat ID is accepted, so someone who finds the bot cannot control it.
/revoke to @BotFather to issue a new one.Common problems
| Symptom | Cause and fix |
|---|---|
| Alarm right after power-up | The PIR is warming up. Wait 60 seconds (the code already ignores it) or raise WARMUP_MS. |
| Random false alarms | Supply noise (voltage dips while the ESP32 transmits WiFi), a sunny window, or an air conditioner or fan blowing at the sensor. Use a good supply, add a 100 µF capacitor near the PIR VCC pin, re-aim the sensor and lower the sensitivity. |
bot.sendMessage returns false | Wrong token or chat ID, you never pressed Start, or an invalid certificate/clock. Test by opening https://api.telegram.org/bot<TOKEN>/getMe in a browser. |
| The /arm command is ignored | Wrong CHAT_ID (it is a string comparison) or the bot was not started. Print bot.messages[i].chat_id to Serial to check. |
| Messages arrive a few seconds late | Normal: TLS handshake plus network latency. Do not send messages from an interrupt handler; reading the pin inside loop() is deliberate. |
| Stops sending after running a while | WiFi dropped. connectWiFi() handles it; if it still fails, check signal strength and call ESP.restart() after a long disconnection. |
Ideas to extend it
- Add a button (or a door contact) to disarm locally.
- Add a buzzer through a transistor for a local alarm.
- Attach an ESP32-CAM to send a photo with the alert: see the ESP32-CAM article and the library's
sendPhotofunction. - Update the firmware remotely once it is mounted on the wall: see OTA over WiFi.
- Battery operation needs deep sleep: the ESP32 can wake on an external interrupt (
esp_sleep_enable_ext0_wakeup) when the PIR goes high. The HC-SR501 itself draws ~50 µA, so consider an AM312 module for battery use.
Summary
- The PIR needs ~60 seconds to warm up; act only on the rising edge of OUT.
- Always keep a cooldown between alerts to avoid spam.
- Accept commands only from your own chat ID and keep the token secret.