Skip to content

Tutorial

Node-RED Telegram and Email Alerts for PIR Motion (ESP32 + MQTT)

Turn ESP32 PIR motion events into Telegram or email alerts with Node-RED: MQTT sketch, edge detection and cooldown, Telegram bot and SMTP setup, and fixes.

  • 5 min read
  • Updated November 2, 2026
Node-RED Telegram and Email Alerts for PIR Motion (ESP32 + MQTT)

Quick answer: to get PIR motion alerts from Node-RED on Telegram or email, have the ESP32 publish 1 (motion) and 0 (clear) to an MQTT topic. In Node-RED, use an mqtt in node feeding a Function node that only reacts to a 0→1 change and enforces a cooldown (for example 60 s). Wire its outputs to a telegram sender node (from node-red-contrib-telegrambot, using a bot made with @BotFather and your chat ID) and/or an email node (from node-red-node-email, using an SMTP app password). Without the edge-detection and cooldown, one person walking past can trigger dozens of messages.

You needNotes
ESP32 (or ESP8266) + HC-SR501 PIR moduleHC-SR501 runs on 5 V and outputs a 3.3 V logic signal, safe for ESP32 inputs
MQTT broker (Mosquitto)See install Mosquitto
Node-REDSee install Node-RED
Telegram account and/or an email account with SMTP accessGmail needs 2-step verification and an App Password

The flow below handles the real-world problems: sensor hold time, retriggers, invalid payloads, Node-RED restarts and failed deliveries, so alerts stay useful instead of noisy.

Rising-edge detection plus a 60-second cooldown turns four motion events into two alerts

1. Wire the PIR sensor and publish clean MQTT messages

HC-SR501 pinESP32 pin
VCC5V (VIN)
OUTGPIO27
GNDGND

On the HC-SR501, the two potentiometers set sensitivity (range, roughly 3–7 m) and hold time (how long OUT stays HIGH after motion, from a few seconds to several minutes). Set hold time near minimum for alerts and let Node-RED handle the cooldown. The jumper selects single trigger (L) or repeat trigger (H). After power-up the module needs up to a minute to settle, and it may give false triggers during that time.

The sketch publishes only when the output changes, so Node-RED gets one 1 at the start of motion and one 0 when it clears:

sketch.ino
#include <WiFi.h>
#include <PubSubClient.h>

const char* WIFI_SSID = "REPLACE_WITH_WIFI";
const char* WIFI_PASS = "REPLACE_WITH_WIFI_PASSWORD";
const char* MQTT_HOST = "192.168.1.50";
const char* MQTT_USER = "pir01";
const char* MQTT_PASS = "REPLACE_WITH_MQTT_PASSWORD";
const char* TOPIC     = "solderhub/home/entry/pir/state";
const int   PIR_PIN   = 27;

WiFiClient net;
PubSubClient mqtt(net);
int lastState = -1;

void setup() {
  Serial.begin(115200);
  pinMode(PIR_PIN, INPUT);
  WiFi.begin(WIFI_SSID, WIFI_PASS);
  while (WiFi.status() != WL_CONNECTED) delay(250);
  mqtt.setServer(MQTT_HOST, 1883);
}

void loop() {
  if (!mqtt.connected()) {
    if (mqtt.connect("solderhub-pir01", MQTT_USER, MQTT_PASS)) lastState = -1; // re-send state
    else { delay(2000); return; }
  }
  mqtt.loop();

  int state = digitalRead(PIR_PIN);
  if (state != lastState) {
    mqtt.publish(TOPIC, state ? "1" : "0");
    Serial.printf("PIR -> %d\n", state);
    lastState = state;
  }
  delay(50);
}

New to MQTT on the ESP32? Start with ESP32 MQTT publish/subscribe.

2. Build the Node-RED flow: rising edge and cooldown

Import or build this flow:

mqtt in (solderhub/home/entry/pir/state) → function "motion filter" (2 outputs) → output 1: telegram sender, output 2: e-mail

Add a catch node → debug node on the same tab so delivery errors are visible. In the Function node's Setup tab, set Outputs to 2, then paste:

script.js
// Accepts 1/0, "1"/"0", true/false. Alerts only on a 0 -> 1 change, max once per cooldown.
const COOLDOWN_MS = 60 * 1000;
const AREA = "Entry";

let raw = msg.payload;
if (typeof raw === "string") raw = raw.trim().toLowerCase();
const state = (raw === 1 || raw === "1" || raw === true || raw === "true") ? 1
: (raw === 0 || raw === "0" || raw === false || raw === "false") ? 0 : null;
if (state === null) { node.warn("Ignored PIR payload: " + JSON.stringify(msg.payload)); return null; }

const previous = context.get("pirState") ?? 0;
context.set("pirState", state);
if (state !== 1 || previous === 1) return null;          // not a new motion event

const now = Date.now();
const lastAlertAt = context.get("lastAlertAt") ?? 0;
if (now - lastAlertAt < COOLDOWN_MS) {
  node.status({ fill: "yellow", shape: "ring", text: "suppressed (cooldown)" });
  return null;
}
context.set("lastAlertAt", now);

const when = new Date(now).toLocaleString();
const text = "Motion detected: " + AREA + " at " + when;
node.status({ fill: "green", shape: "dot", text: "alert " + when });

const telegram = { payload: { chatId: Number(env.get("TELEGRAM_CHAT_ID")), type: "message", content: text } };
const email    = { topic: "Motion alert: " + AREA, payload: text };
return [telegram, email];

How the filter works

PartWhy
Payload normaliserMQTT can deliver 1, "1" or true depending on node settings; the string "0" would otherwise count as true
previous === 1 checkIgnores repeated HIGH messages while motion continues
lastAlertAt + COOLDOWN_MSAt most one alert per minute, however often the sensor retriggers
Two outputsTelegram and email get correctly shaped messages; delete one wire if you only want one channel
node.statusShows "alert" or "suppressed" under the node, so you can watch it work

No-code alternative: a filter node (block unless value changes) followed by a delay node in Rate limit mode (1 msg per minute, drop intermediate messages) does almost the same job, and it's easier for beginners to read.

3. Send the alert to Telegram

  1. In Telegram, open @BotFather, send /newbot, choose a name and a username ending in bot. BotFather replies with the bot token.
  2. Open a chat with your new bot and send it any message (bots can't message you first).
  3. Get your chat ID: open https://api.telegram.org/bot<TOKEN>/getUpdates in a browser and read "chat":{"id":…}. (Group chat IDs are negative, often starting with -100.)
  4. In Node-RED, Manage palette → Install → node-red-contrib-telegrambot. Drag in a sender node, click the pencil next to Bot, enter the bot name and token, and deploy.
  5. Put the chat ID in an environment variable named TELEGRAM_CHAT_ID (in the Node-RED settings or the flow tab's Environment Variables), then deploy.

The sender expects exactly this payload shape, which the Function node builds:

config.json
{ "chatId": 123456789, "type": "message", "content": "Motion detected: Entry at 21:14:05" }

Test with an inject node sending 1 into the Function node before involving the real sensor. To send a camera snapshot instead of text, use type: "photo" with an image URL or buffer as content; the ESP32-CAM Telegram bot project shows a camera-side approach.

Keep the token in the bot's config node (Node-RED stores it in the encrypted credentials file), not in Function code or exported flows. Anyone with the token can control the bot; if it leaks, send /revoke to BotFather.

4. Send the alert by email

  1. Install node-red-node-email from the palette and drag in an e-mail (output) node.
  2. Set To to your address. With Gmail: Server smtp.gmail.com, Port 465, Use secure connection ticked, Userid = your Gmail address, Password = a 16-character App Password (Google Account → Security → 2-Step Verification → App passwords). Your normal Gmail password will be rejected.
  3. Other providers: use their SMTP host; port 465 means TLS from the start (tick secure), port 587 means STARTTLS (untick secure).

The node uses msg.topic as the subject and msg.payload as the body, which the Function node's second output provides. Email can arrive minutes late or land in spam, so use Telegram for anything time-sensitive and email for a record.

Reliability and privacy checklist

RiskWhat to do
Alert floodsRising edge + cooldown (above); add a daily summary if a sensor is busy
False alarmsKeep the PIR away from heaters, air vents and direct sunlight; let it warm up for a minute after power-on
Silent failurescatch node → debug (or a second notification channel) so token or SMTP errors show up
Restart behaviourFunction context resets on restart; use persistent context storage if a missed cooldown matters
Sensor offline looks like "no motion"Add MQTT Last Will to the ESP32 and alert on offline
Leaked secretsTokens and passwords only in config nodes or environment variables, never in exported flows
Over-relianceTelegram/email alerts are awareness, not a certified alarm system

Troubleshooting

SymptomLikely causeFix
Telegram node says "bot not initialized"No bot config selected, or invalid tokenOpen the sender, select or re-enter the bot with the BotFather token, deploy
ETELEGRAM: 409 Conflict: terminated by other getUpdates requestThe same bot token is polling from two places (two Node-RED instances, or a test script)Use the token in one place only, or create a second bot
"chatId is empty" / message not deliveredTELEGRAM_CHAT_ID not set, or you never messaged the bot firstSet the variable, message the bot, check the chat ID with getUpdates
403 Forbidden: bot was blocked by the userChat with the bot was deleted or blockedUnblock the bot and press Start
Email: Invalid login / 535Normal password used, or 2-step verification offUse an App Password
Email: timeoutPort/secure setting mismatch or blocked port465 + secure, or 587 without secure; some ISPs block outbound SMTP
Dozens of alertsPayload is a string the filter doesn't recognise, or no cooldownWatch the debug output of the mqtt in node; use the normaliser above
No alerts at allTopic mismatch, PIR still warming up, or first message was 1 with previous stuck at 1Debug the mqtt in node; send 0 then 1 from an inject node
Random triggers at nightHeat sources, insects, unstable 5 VRe-aim the sensor, lower sensitivity, use a decent supply
Duplicate alert after deployContext reset clears lastAlertAtEnable persistent context (contextStorage in settings.js)

FAQ

Which Telegram node should I use in Node-RED? node-red-contrib-telegrambot is the most widely used. It has sender, receiver, command and event nodes, so the same bot can also accept commands like /arm and /disarm.

Is Telegram free for alerts? Yes. Bots and messages are free; Telegram rate-limits very frequent messages to the same chat, which the cooldown avoids anyway.

Can I send alerts without Node-RED? Yes, the ESP32 can call the Telegram Bot API directly over HTTPS. Node-RED is better when several sensors share one alert policy, or you want email, logging and a dashboard too.

Can I arm and disarm the alerts? Store an armed flag in flow context, set it from a dashboard switch or a Telegram /arm command, and have the Function node return null when disarmed.

How do I stop alerts while I'm home? Use the arm flag above, or schedule it: see Node-RED automation with schedules and context.

Next steps

Official references: node-red-contrib-telegrambot, node-red-node-email and Securing Node-RED.

Continue learning

Related articles

All articles

Signal In

Built from what makers search for

The lookups piling up in SolderHub's search bar every day shape what we publish next — new component pages, board guides, and firmware notes, sent out as they go live.

By subscribing you agree to our Privacy Policy. Unsubscribe anytime.