Smart homeNotifications

ESP32 motion alarm with a PIR sensor and Telegram alerts

Difficulty: easy · Time: ~1 hour · Cost: ~$6–8

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

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.

Wiring

ESP32 DevKitPIR HC-SR501VIN (5V)GPIO27GNDVCCOUTGNDred: 5V poweryellow: signalgrey: GND
Figure 1: Wiring. Only three wires are needed. See GPIO pins to avoid for pin selection; GPIO27 is a free-to-use pin.

Creating the Telegram bot

  1. In Telegram, find @BotFather, send /newbot, then choose a name and a username ending in bot. BotFather returns a token like 123456789:AA.... It controls your bot, so never publish it.
  2. Open your new bot and press Start (a bot can only message people who have started a conversation).
  3. 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.

Note: never commit the token to a public GitHub repository. If it leaks, send /revoke to @BotFather to issue a new one.

Common problems

SymptomCause and fix
Alarm right after power-upThe PIR is warming up. Wait 60 seconds (the code already ignores it) or raise WARMUP_MS.
Random false alarmsSupply 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 falseWrong 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 ignoredWrong 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 lateNormal: 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 whileWiFi dropped. connectWiFi() handles it; if it still fails, check signal strength and call ESP.restart() after a long disconnection.

Ideas to extend it

Summary