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 need | Notes |
|---|---|
| ESP32 (or ESP8266) + HC-SR501 PIR module | HC-SR501 runs on 5 V and outputs a 3.3 V logic signal, safe for ESP32 inputs |
| MQTT broker (Mosquitto) | See install Mosquitto |
| Node-RED | See install Node-RED |
| Telegram account and/or an email account with SMTP access | Gmail 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.
1. Wire the PIR sensor and publish clean MQTT messages
| HC-SR501 pin | ESP32 pin |
|---|---|
| VCC | 5V (VIN) |
| OUT | GPIO27 |
| GND | GND |
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:
#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:
// 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
| Part | Why |
|---|---|
| Payload normaliser | MQTT can deliver 1, "1" or true depending on node settings; the string "0" would otherwise count as true |
previous === 1 check | Ignores repeated HIGH messages while motion continues |
lastAlertAt + COOLDOWN_MS | At most one alert per minute, however often the sensor retriggers |
| Two outputs | Telegram and email get correctly shaped messages; delete one wire if you only want one channel |
node.status | Shows "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
- In Telegram, open @BotFather, send
/newbot, choose a name and a username ending inbot. BotFather replies with the bot token. - Open a chat with your new bot and send it any message (bots can't message you first).
- Get your chat ID: open
https://api.telegram.org/bot<TOKEN>/getUpdatesin a browser and read"chat":{"id":…}. (Group chat IDs are negative, often starting with-100.) - 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.
- 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:
{ "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
- Install node-red-node-email from the palette and drag in an e-mail (output) node.
- Set To to your address. With Gmail: Server
smtp.gmail.com, Port465, 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. - 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
| Risk | What to do |
|---|---|
| Alert floods | Rising edge + cooldown (above); add a daily summary if a sensor is busy |
| False alarms | Keep the PIR away from heaters, air vents and direct sunlight; let it warm up for a minute after power-on |
| Silent failures | catch node → debug (or a second notification channel) so token or SMTP errors show up |
| Restart behaviour | Function 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 secrets | Tokens and passwords only in config nodes or environment variables, never in exported flows |
| Over-reliance | Telegram/email alerts are awareness, not a certified alarm system |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| Telegram node says "bot not initialized" | No bot config selected, or invalid token | Open the sender, select or re-enter the bot with the BotFather token, deploy |
ETELEGRAM: 409 Conflict: terminated by other getUpdates request | The 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 delivered | TELEGRAM_CHAT_ID not set, or you never messaged the bot first | Set the variable, message the bot, check the chat ID with getUpdates |
403 Forbidden: bot was blocked by the user | Chat with the bot was deleted or blocked | Unblock the bot and press Start |
Email: Invalid login / 535 | Normal password used, or 2-step verification off | Use an App Password |
| Email: timeout | Port/secure setting mismatch or blocked port | 465 + secure, or 587 without secure; some ISPs block outbound SMTP |
| Dozens of alerts | Payload is a string the filter doesn't recognise, or no cooldown | Watch the debug output of the mqtt in node; use the normaliser above |
| No alerts at all | Topic mismatch, PIR still warming up, or first message was 1 with previous stuck at 1 | Debug the mqtt in node; send 0 then 1 from an inject node |
| Random triggers at night | Heat sources, insects, unstable 5 V | Re-aim the sensor, lower sensitivity, use a decent supply |
| Duplicate alert after deploy | Context reset clears lastAlertAt | Enable 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
- Node-RED with Mosquitto: publish and subscribe: the MQTT basics this flow builds on.
- Reliable Node-RED flows with subflows and Catch: turn this filter into a reusable subflow for every sensor.
- Node-RED Dashboard 2.0 setup: add an arm/disarm switch and a motion log.
- PIR alerts with Blynk instead: phone push notifications without running a server.
- MQTT topic naming best practices.
Official references: node-red-contrib-telegrambot, node-red-node-email and Securing Node-RED.




