DIY ESP32 Home Alarm with PIR, Shock Sensor & Telegram

Advertisement

A home alarm does not have to be complicated. This guide shows how to build a simple, reliable DIY alarm with an ESP32, a PIR motion sensor, a shock (vibration) sensor and a wired door loop. It has an exit and entry delay, a siren relay, and sends alerts to your phone through Telegram. The alarm logic runs locally, so the siren still works if your Wi-Fi is down.

It is a learning project and a useful add-on, not a certified security product. For a high-value property, use a professionally installed and monitored system as well.

How the alarm works

StateWhat happens
DisarmedSensors are ignored. The armed LED is off.
Exit delay (30 s)You press the button or send /arm and have 30 seconds to leave.
ArmedThe shock sensor triggers the alarm immediately. The door loop or the PIR starts the entry delay.
Entry delay (20 s)You have 20 seconds to disarm. Otherwise the alarm triggers.
AlarmThe siren sounds, a Telegram message is sent, and the memory LED stays on until you re-arm. The siren stops by itself after 2 minutes and the system keeps watching.

What you need

PartNotes
ESP32 development boardAny ESP32 DevKit.
PIR sensor HC-SR501Powered from 5 V, its output is 3.3 V, safe for the ESP32.
Shock / vibration sensor moduleWith a potentiometer to adjust sensitivity (for example an SW-420 type).
Magnetic reed contacts (normally closed)Wired in a loop to ground. An open door or a cut wire triggers the alarm.
Relay module5 V relay board that can switch your siren current.
12 V sirenChoose a model suited to your local noise rules.
Certified 12 V power supply and backup batteryKeep mains wiring away from the alarm box. A float charger keeps a lead-acid backup battery ready.
5 V buck converterPowers the ESP32, the PIR and the relay board from 12 V.
2 LEDs with resistors, push buttonArmed LED, event-memory LED, arm/disarm button.

Wiring

DeviceESP32 pinNotes
PIR outputGPIO27PIR VCC to 5 V, GND to GND.
Shock sensor outputGPIO26Check whether your module outputs HIGH or LOW on vibration and set SHOCK_ACTIVE_LEVEL.
Door loop (NC contacts in series)GPIO14 and GNDInternal pull-up is used. Closed loop = LOW = normal.
Siren relay inputGPIO25The siren is powered from the 12 V supply through the relay contacts.
Memory LEDGPIO2Through a resistor to GND (also the on-board LED on many boards).
Armed LEDGPIO4Through a resistor to GND.
Arm/disarm buttonGPIO33 and GNDInternal pull-up is used.
  • These pins avoid the ESP32 pins reserved for the flash memory (GPIO6 to 11), which many Arduino-style examples break by mistake.
  • A bare relay coil needs a flyback diode such as a 1N4007 across it. Most relay modules already include one.
  • Give the PIR a minute to warm up after power-up. The code ignores it for the first 60 seconds.

Set up the Telegram bot

  1. In Telegram, open @BotFather, send /newbot and follow the steps. Copy the bot token.
  2. Send any message to your new bot, then open a bot such as @userinfobot to find your chat ID.
  3. Put both values in the sketch. The code accepts commands only from your chat ID, so nobody else can disarm your alarm.
  4. Keep the bot token secret. Anyone with the token can read and send messages as your bot.

The ESP32 code

Install these libraries in the Arduino IDE: UniversalTelegramBot by Brian Lough and ArduinoJson (required by the bot). Select your ESP32 board, edit the settings at the top and upload.

/*
  DIY home alarm with ESP32: PIR + shock sensor + door loop, entry/exit delay,
  siren relay and Telegram alerts/commands.
  - The alarm logic runs locally. If Wi-Fi is down the siren still works.
  - Telegram commands are accepted only from your own chat ID.
  Libraries: UniversalTelegramBot (Brian Lough), ArduinoJson (required by the bot)
*/
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>

// ---------- User settings ----------
const char* WIFI_SSID     = "YOUR_WIFI_NAME";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
const char* BOT_TOKEN     = "YOUR_TELEGRAM_BOT_TOKEN";   // from @BotFather
const char* CHAT_ID       = "YOUR_TELEGRAM_CHAT_ID";     // only this chat may control the alarm

// ---------- Pins (ESP32 DevKit) ----------
const int PIN_PIR     = 27;   // HC-SR501 output (3.3 V, active HIGH)
const int PIN_SHOCK   = 26;   // vibration/shock module digital output
const int PIN_DOOR    = 14;   // normally-closed loop to GND (open or cut wire = alarm)
const int PIN_SIREN   = 25;   // relay module input for the 12 V siren
const int PIN_LED_MEM = 2;    // event memory LED (on after an alarm, until re-armed)
const int PIN_LED_ARM = 4;    // ON when armed
const int PIN_BUTTON  = 33;   // arm/disarm button to GND

const bool SIREN_ACTIVE_HIGH = true;    // false for active-LOW relay boards
const int  SHOCK_ACTIVE_LEVEL = HIGH;   // check your module (many give LOW on vibration)

// ---------- Timing ----------
const unsigned long EXIT_DELAY_MS   = 30000;   // time to leave after arming
const unsigned long ENTRY_DELAY_MS  = 20000;   // time to disarm after opening the door
const unsigned long SIREN_MAX_MS    = 120000;  // siren stops by itself (check local rules)
const unsigned long PIR_WARMUP_MS   = 60000;   // HC-SR501 needs about a minute after power-up
const unsigned long POLL_INTERVAL_MS = 3000;   // Telegram polling period

enum State { DISARMED, EXIT_DELAY, ARMED, ENTRY_DELAY, ALARM };
State state = DISARMED;
unsigned long stateSince = 0;
bool eventMemory = false;
String cause = "";
bool alertPending = false;

WiFiClientSecure securedClient;
UniversalTelegramBot bot(BOT_TOKEN, securedClient);
unsigned long lastPoll = 0;
unsigned long lastWifiAttempt = 0;

const char* stateName(State s) {
  switch (s) {
    case DISARMED:    return "DISARMED";
    case EXIT_DELAY:  return "ARMING (exit delay)";
    case ARMED:       return "ARMED";
    case ENTRY_DELAY: return "ENTRY DELAY";
    case ALARM:       return "ALARM";
  }
  return "?";
}

void setSiren(bool on) {
  digitalWrite(PIN_SIREN, (on == SIREN_ACTIVE_HIGH) ? HIGH : LOW);
}

void setState(State s) {
  state = s;
  stateSince = millis();
  digitalWrite(PIN_LED_ARM, (s == DISARMED) ? LOW : HIGH);
  digitalWrite(PIN_LED_MEM, eventMemory ? HIGH : LOW);
  if (s != ALARM) setSiren(false);
  Serial.printf("State: %s\n", stateName(s));
}

void arm() {
  eventMemory = false;     // memory is cleared when the system is re-armed
  setState(EXIT_DELAY);
}

void disarm() {
  setState(DISARMED);
}

void triggerAlarm(const String& why) {
  cause = why;
  eventMemory = true;
  alertPending = true;
  setState(ALARM);
  setSiren(true);          // siren first, notifications after
}

bool pirActive()  { return millis() > PIR_WARMUP_MS && digitalRead(PIN_PIR) == HIGH; }
bool shockActive(){ return digitalRead(PIN_SHOCK) == SHOCK_ACTIVE_LEVEL; }
bool doorOpen()   { return digitalRead(PIN_DOOR) == HIGH; }   // loop open or cable cut

void handleButton() {
  static bool lastLevel = HIGH;
  static unsigned long lastChange = 0;
  bool level = digitalRead(PIN_BUTTON);
  if (level != lastLevel && millis() - lastChange > 50) {
    lastChange = millis();
    lastLevel = level;
    if (level == LOW) {                    // pressed
      if (state == DISARMED) arm(); else disarm();
    }
  }
}

void updateAlarm() {
  switch (state) {
    case DISARMED:
      break;
    case EXIT_DELAY:
      if (millis() - stateSince >= EXIT_DELAY_MS) setState(ARMED);
      break;
    case ARMED:
      if (shockActive()) {
        triggerAlarm("Shock sensor");
      } else if (doorOpen()) {
        cause = "Door loop opened or cut";
        setState(ENTRY_DELAY);
      } else if (pirActive()) {
        cause = "Motion (PIR)";
        setState(ENTRY_DELAY);
      }
      break;
    case ENTRY_DELAY:
      if (millis() - stateSince >= ENTRY_DELAY_MS) triggerAlarm(cause);
      break;
    case ALARM:
      if (millis() - stateSince >= SIREN_MAX_MS) {
        setSiren(false);
        setState(ARMED);                   // keep watching, memory LED stays on
      }
      break;
  }
}

void handleTelegram() {
  if (WiFi.status() != WL_CONNECTED) return;

  if (alertPending) {
    String msg = "ALARM! Cause: " + cause;
    if (bot.sendMessage(CHAT_ID, msg, "")) alertPending = false;
  }

  if (millis() - lastPoll < POLL_INTERVAL_MS) return;
  lastPoll = millis();

  int count = bot.getUpdates(bot.last_message_received + 1);
  for (int i = 0; i < count; i++) {
    String chatId = String(bot.messages[i].chat_id);
    String text   = bot.messages[i].text;
    if (chatId != String(CHAT_ID)) continue;          // ignore everybody else

    if (text == "/arm") {
      arm();
      bot.sendMessage(CHAT_ID, "Arming. You have 30 s to leave.", "");
    } else if (text == "/disarm") {
      disarm();
      bot.sendMessage(CHAT_ID, "Alarm disarmed.", "");
    } else if (text == "/status") {
      String msg = String("Status: ") + stateName(state);
      if (eventMemory) msg += "\nLast alarm: " + cause;
      bot.sendMessage(CHAT_ID, msg, "");
    }
  }
}

void keepWifiAlive() {
  if (WiFi.status() == WL_CONNECTED) return;
  if (millis() - lastWifiAttempt > 10000) {
    lastWifiAttempt = millis();
    WiFi.disconnect();
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(PIN_PIR, INPUT);
  pinMode(PIN_SHOCK, INPUT);
  pinMode(PIN_DOOR, INPUT_PULLUP);
  pinMode(PIN_BUTTON, INPUT_PULLUP);
  pinMode(PIN_SIREN, OUTPUT);
  pinMode(PIN_LED_MEM, OUTPUT);
  pinMode(PIN_LED_ARM, OUTPUT);
  setSiren(false);

  WiFi.mode(WIFI_STA);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  securedClient.setCACert(TELEGRAM_CERTIFICATE_ROOT);   // validate Telegram's certificate
  configTime(0, 0, "pool.ntp.org");                      // TLS needs a correct clock
  setState(DISARMED);
}

void loop() {
  handleButton();
  updateAlarm();      // local logic first: never depends on Wi-Fi or Telegram
  keepWifiAlive();
  handleTelegram();
}
DIY ESP32 Home Alarm with PIR, Shock Sensor

How the code works

  • Local logic first: the state machine runs before any network code. The siren is switched on before the Telegram message is sent.
  • Entry and exit delays: they give you time to leave and to disarm, which avoids most false alarms.
  • Tamper detection: the normally-closed door loop triggers if someone opens the door or cuts the wire.
  • Event memory: the memory LED remains on after an alarm until you arm the system again, so you can see what happened while you were away.
  • Siren time limit: the siren stops after 2 minutes. Many countries limit how long an alarm may sound, so check your local rules and adjust SIREN_MAX_MS.
  • Secure Telegram connection: the sketch validates Telegram's certificate and syncs the clock with NTP, which TLS needs.

Testing

  1. Disconnect the siren relay output first and test with the LEDs only.
  2. Send /status in Telegram. The bot should reply with the state.
  3. Send /arm, wait for the exit delay, then open the door loop. The system should enter the entry delay and then trigger.
  4. Tap the shock sensor and check the immediate alarm. Adjust the potentiometer if it is too sensitive or not sensitive enough.
  5. Reconnect the siren, warn your neighbours, and do a short real test.

Reducing false alarms

  • Do not point the PIR at windows, heaters, radiators or sunlit surfaces, and keep it away from air vents.
  • Mount the shock sensor on a window frame or door, not on a wall near road traffic. Start with a low sensitivity and increase it step by step.
  • Use the entry delay for doors you normally use.
  • For pets, choose a PIR mounting height and angle that avoids the floor area.

Remote controls and rolling codes

A fixed-code 433 MHz remote is easy to copy with a cheap software-defined radio. A rolling-code remote is better, but it is not unbreakable: some systems are weakened by replay and jamming attacks, and the older KeeLoq scheme has known cryptographic weaknesses. For this project, arm and disarm with the Telegram bot, or build a keypad or RFID reader. See our ESP32 keypad door lock and RFID smart door lock guides.

Also note that a button placed on the entry path lets an intruder disarm the alarm during the entry delay. Put it somewhere out of sight, or use a keypad, RFID or the Telegram command.

Power and the backup battery

  • Use a certified 12 V power supply. Do not wire mains voltage onto your alarm board.
  • Add a backup battery with a proper float charger so the alarm keeps running during a power cut.
  • Alarms often get tampered with by cutting power, so a backup battery matters more than any extra sensor.

What about GSM and SMS alerts?

A SIM800L module only works on 2G networks, and 2G is being switched off in many countries, so check your network first. It also needs a stable 3.4 to 4.4 V supply that can deliver up to 2 A peaks, which a 3.3 V ESP32 pin cannot provide. For cellular alerts, consider an LTE module such as the SIM7600 or A7670 series. For most homes, Wi-Fi notifications through Telegram are simpler and more reliable.

Troubleshooting

SymptomLikely cause and fix
Alarm triggers right after armingDoor loop open, a reed contact misaligned, or the shock sensor active level is wrong.
PIR triggers constantlyHeat source or sunlight in view, or the warm-up period has not finished.
No Telegram messagesWrong bot token or chat ID, no Wi-Fi, or you have not sent a first message to the bot.
ESP32 reboots when the siren startsPower supply voltage drop. Use a stronger supply and keep the siren supply separate from the ESP32 feed.
Siren never stopsCheck SIREN_ACTIVE_HIGH for your relay board and test the relay input wiring.

Frequently asked questions

Wired or wireless sensors?

Wired sensors are more reliable (no batteries, no radio interference) and a wired loop can detect cable cuts. Wireless sensors are easier to install in difficult places. Many people use wired sensors for doors and wireless ones elsewhere.

Should I require two sensors before triggering?

Requiring two sensors reduces false alarms, but it can also miss a real intrusion that only triggers one sensor, such as a window shock with no motion in the room. Use entry delays first, and add confirmation logic only where needed.

Can I add more sensors?

Yes. Add more normally-closed contacts in the door loop, or use extra GPIO pins and treat them as additional zones in the state machine.

Can I connect it to Home Assistant?

Yes. The same logic can publish its state over MQTT. See our ESP32 energy monitor guide for the MQTT and Home Assistant setup.

DIY ESP32 Home Alarm with PIR, Diagram

Related projects

More in our ESP32 Smart Home projects hub.

Conclusion

With an ESP32, three sensors and a relay you get a flexible home alarm with delays, tamper detection, event memory and phone alerts. Test it carefully, mind your local noise and privacy rules, and add a backup battery. Questions about the sensors or the Telegram setup? Leave a comment below.

No comments