What You Will Build
This project turns an ESP32-CAM into a small motion-alert camera that you can arm and disarm from your phone. A PIR sensor watches a room or doorway. When it detects movement while the system is armed, the board does three things: it raises a Blynk event that pushes a notification to your phone, it switches on the camera's flash LED, takes a photo, and it sends that photo privately to your phone through a Telegram bot, so you can see what moved.
The design deliberately has no open web server on the camera. The ESP32-CAM only makes outgoing connections, so there is no camera page for anyone on your network, or the internet, to browse. That removes the biggest weakness of most hobby camera projects.
Along the way you will learn how the ESP32-CAM's pins really work (most are taken), why its power supply matters more than almost anything else, how to design alert logic that does not spam you, and how to keep a cloud notification path and a photo path independent so one failing does not hide the other.
An honest scope note. A PIR sensor detects changes in infrared heat. It does not recognise a person, and it can be fooled by pets, heaters and sunlight. This is a learning prototype and a useful extra pair of eyes, not a certified alarm. Do not rely on it as the only protection for a home or business.
How the System Works
The flow is simple, and each stage can be tested on its own:
- PIR output goes HIGH when it sees movement.
- The firmware checks that the system is armed (past its exit delay) and that the PIR has finished its warm-up.
- It detects a rising edge, a change from no motion to motion, rather than reacting to every loop while the output is HIGH.
- A cooldown timer suppresses further alerts for 60 seconds.
- The board sends a Blynk event, updates the dashboard, takes a fresh photo with the flash, and uploads the photo to Telegram.
Blynk is used for what it does well: a dashboard with an arm switch and status, and reliable push notifications. Telegram is used only as a private delivery channel for the image. The two paths are independent, so you still get the alert if the photo upload fails, and the photo if Blynk is briefly offline.
Components
7 itemsNeed these parts? Get this build sheet by email
Parts list with buy links, plus new builds as they're published. By subscribing you agree to our Privacy Policy. Unsubscribe anytime.
Know Your ESP32-CAM Before Wiring
The AI-Thinker ESP32-CAM packs a camera, PSRAM, a microSD slot, a flash LED and a status LED onto a very small board, and most of the chip's pins are already in use. Wiring a sensor to a random pin is the number one cause of "my camera stopped working".
| GPIO | What it does on this board | Usable for a sensor? |
|---|---|---|
| 0 | Camera clock, and the boot-mode pin | No |
| 1, 3 | UART0 TX and RX, used for programming and logs | Avoid |
| 2 | microSD data, and it must be low or floating at boot | Risky |
| 4 | Flash LED and microSD data | Only if you accept the LED |
| 12 | microSD data, and a strapping pin: HIGH at boot can stop the board booting | No |
| 13 | microSD data, otherwise free | Yes, our PIR pin |
| 14, 15 | microSD clock and command | Only if no SD card is used |
| 16 | Used by the PSRAM | No |
| 33 | Red status LED, active LOW | Used for status |
| 5, 18, 19, 21, 22, 23, 25, 26, 27, 32, 34, 35, 36, 39 | Camera data and control lines | No |
Two more facts matter. The only pins on the header are 12, 13, 14, 15, 2 and 4, and all of them belong to ADC2, which cannot be read while Wi-Fi is on. So an analog sensor on an ESP32-CAM is not a realistic option, and digital sensors such as a PIR are the right fit. Also, the board has no USB port, so you program it through the UART pins with an adapter.
For a full pin reference, see the ESP32-CAM Pinout Guide, and for first-time programming see ESP32-CAM Programming: Getting Started.
Wiring
The circuit has only three connections for the PIR:
| HC-SR501 PIR | ESP32-CAM |
|---|---|
| VCC | 5V |
| GND | GND |
| OUT | GPIO 13 |
The HC-SR501 runs from 5 V to 20 V, and its output is a 3.3 V logic signal, so it connects directly to the ESP32 pin without a level shifter.
Setting Up the PIR Module
The module has two small potentiometers and a jumper. One sets sensitivity (range, roughly 3 to 7 m) and the other sets the hold time, how long OUT stays HIGH after movement (about 3 seconds to several minutes). Start with the hold time at its minimum, because the firmware handles repeat alerts itself. The jumper selects repeat trigger mode (H), where the output stays HIGH while motion continues, or single trigger mode (L). Leave it on H.
After power-up the sensor needs about 30 to 60 seconds to settle, and it can give false triggers during that time. The firmware ignores the PIR for the first 30 seconds after boot for this reason.
Programming Connections
To upload code, connect the FTDI adapter set to 3.3 V logic:
| FTDI | ESP32-CAM |
|---|---|
| GND | GND |
| 5V | 5V |
| TX | U0R (GPIO 3) |
| RX | U0T (GPIO 1) |
Also connect GPIO 0 to GND with a jumper to enter flash mode. After uploading, remove that jumper and press the reset button to run the program.
⚠️ Warning
Power is the first thing to fix. The ESP32-CAM draws sharp current spikes when the camera starts and the Wi-Fi radio transmits, and the flash LED adds more. A weak USB port or a thin cable causes brownouts, which show up as random resets, a "Brownout detector was triggered" message, or the camera failing to start. Use a 5 V 2 A supply, a short thick cable, and a 470 to 1000 µF capacitor across 5V and GND next to the board. Do not "fix" it by disabling the brownout detector in software, because that only hides the problem.
Set Up the Services
Create the Blynk Template
- In Blynk.Console, create a template with hardware ESP32 and connection WiFi.
- Add these datastreams (all virtual pins):
| Pin | Name | Type | Purpose |
|---|---|---|---|
| V0 | Armed | Integer 0 to 1 | Arm or disarm switch |
| V1 | Status | String | Disarmed, Arming, Armed or ALERT |
| V2 | Last motion | String | Time of the last alert |
| V3 | Wi-Fi signal | Integer, dBm | Link quality |
| V4 | Snapshot | Integer 0 to 1 | Button to request a photo now |
- Under Events, create an event with the code
motion_detectedand enable the notification option. The event code is case-sensitive and must match the firmware exactly. - Build a dashboard: a switch on V0, a label on V1 and V2, a gauge on V3 and a button on V4, then create a device from the template. Copy its Template ID, Template Name and Auth Token.
Blynk plans limit the number of datastreams, events and notifications, and these limits change, so check your current plan. If you are short of datastreams, V2 and V3 are the ones to drop.
Create the Telegram Bot
- In Telegram, message @BotFather, send
/newbotand follow the prompts. Copy the bot token it gives you and keep it secret. - Send any message to your new bot so a chat exists.
- Find your chat ID, for example by messaging a bot such as @userinfobot, or by opening
https://api.telegram.org/bot<TOKEN>/getUpdatesin a browser and readingchat→id.
The firmware sends photos only to that one chat ID, so strangers who find the bot cannot receive them.
Arduino IDE Setup
Install the esp32 by Espressif Systems board package, then install the Blynk library (version 1.3.x) from the Library Manager. Select AI Thinker ESP32-CAM as the board. Set Partition Scheme to Huge APP (3MB No OTA/1MB SPIFFS), because the camera, Blynk and TLS together make a large sketch. If you see compile errors with a very new core and the Blynk library, try a core version that Blynk is known to build on, such as 2.0.17.
The Firmware
The sketch is organised around a small state machine: DISARMED, ARMING and ARMED. Switching the app switch on moves it to ARMING, which gives you a 20-second exit delay to leave the room before the PIR is taken seriously. Only in ARMED does a PIR rising edge produce an alert.
Fill in the five settings at the top before uploading: your Wi-Fi details, the three Blynk values, and the Telegram token and chat ID.
// ESP32-CAM + Blynk security prototype
// Board: AI Thinker ESP32-CAM | Partition: Huge APP | Blynk library 1.3.x
#define BLYNK_TEMPLATE_ID "TMPLxxxxxxxx"
#define BLYNK_TEMPLATE_NAME "ESP32-CAM Security"
#define BLYNK_AUTH_TOKEN "YOUR_BLYNK_AUTH_TOKEN"
#define BLYNK_PRINT Serial
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <BlynkSimpleEsp32.h>
#include "esp_camera.h"
#include <time.h>
const char* WIFI_SSID = "YOUR_SSID";
const char* WIFI_PASS = "YOUR_PASSWORD";
const char* TG_BOT_TOKEN = "YOUR_TELEGRAM_BOT_TOKEN";
const char* TG_CHAT_ID = "YOUR_CHAT_ID";
const char* TZ_INFO = "IST-5:30"; // change for your time zone
// ---------- Pins ----------
const uint8_t PIR_PIN = 13;
const uint8_t FLASH_PIN = 4; // flash LED (also microSD data)
// ---------- Timing ----------
const uint32_t PIR_WARMUP_MS = 30000; // ignore the PIR just after boot
const uint32_t EXIT_DELAY_MS = 20000; // time to leave after arming
const uint32_t COOLDOWN_MS = 60000; // minimum gap between alerts
const bool USE_FLASH = true;
// ---------- AI Thinker camera pins ----------
#define PWDN_GPIO_NUM 32
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 0
#define SIOD_GPIO_NUM 26
#define SIOC_GPIO_NUM 27
#define Y9_GPIO_NUM 35
#define Y8_GPIO_NUM 34
#define Y7_GPIO_NUM 39
#define Y6_GPIO_NUM 36
#define Y5_GPIO_NUM 21
#define Y4_GPIO_NUM 19
#define Y3_GPIO_NUM 18
#define Y2_GPIO_NUM 5
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 23
#define PCLK_GPIO_NUM 22
enum State : uint8_t { DISARMED, ARMING, ARMED };
State state = DISARMED;
uint32_t armingStartedAt = 0;
uint32_t lastAlertAt = 0;
bool alertShown = false;
bool prevMotion = false;
volatile bool snapshotRequested = false;
BlynkTimer timer;
// ---------- Camera ----------
bool initCamera() {
camera_config_t c = {};
c.ledc_channel = LEDC_CHANNEL_0;
c.ledc_timer = LEDC_TIMER_0;
c.pin_d0 = Y2_GPIO_NUM; c.pin_d1 = Y3_GPIO_NUM;
c.pin_d2 = Y4_GPIO_NUM; c.pin_d3 = Y5_GPIO_NUM;
c.pin_d4 = Y6_GPIO_NUM; c.pin_d5 = Y7_GPIO_NUM;
c.pin_d6 = Y8_GPIO_NUM; c.pin_d7 = Y9_GPIO_NUM;
c.pin_xclk = XCLK_GPIO_NUM;
c.pin_pclk = PCLK_GPIO_NUM;
c.pin_vsync = VSYNC_GPIO_NUM;
c.pin_href = HREF_GPIO_NUM;
c.pin_sccb_sda = SIOD_GPIO_NUM;
c.pin_sccb_scl = SIOC_GPIO_NUM;
c.pin_pwdn = PWDN_GPIO_NUM;
c.pin_reset = RESET_GPIO_NUM;
c.xclk_freq_hz = 20000000;
c.pixel_format = PIXFORMAT_JPEG;
c.frame_size = FRAMESIZE_SVGA; // 800x600
c.jpeg_quality = 12; // lower number = better quality
c.fb_count = 2;
c.fb_location = CAMERA_FB_IN_PSRAM;
c.grab_mode = CAMERA_GRAB_LATEST;
return esp_camera_init(&c) == ESP_OK;
}
camera_fb_t* captureFresh() {
if (USE_FLASH) { digitalWrite(FLASH_PIN, HIGH); delay(200); }
camera_fb_t* fb = esp_camera_fb_get(); // may be an old frame
if (fb) esp_camera_fb_return(fb);
delay(100);
fb = esp_camera_fb_get(); // fresh frame, exposure settled
if (USE_FLASH) digitalWrite(FLASH_PIN, LOW);
return fb;
}
// ---------- Telegram photo upload (outgoing only, no open port) ----------
bool sendPhotoTelegram(camera_fb_t* fb, const char* caption) {
WiFiClientSecure client;
client.setInsecure(); // prototype only - pin the Telegram certificate before relying on this
if (!client.connect("api.telegram.org", 443)) return false;
const String boundary = "----ESP32CamBoundary";
String head = "--" + boundary + "\r\nContent-Disposition: form-data; name=\"chat_id\"\r\n\r\n";
head += String(TG_CHAT_ID) + "\r\n";
head += "--" + boundary + "\r\nContent-Disposition: form-data; name=\"caption\"\r\n\r\n";
head += String(caption) + "\r\n";
head += "--" + boundary + "\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"alert.jpg\"\r\n";
head += "Content-Type: image/jpeg\r\n\r\n";
const String tail = "\r\n--" + boundary + "--\r\n";
const uint32_t totalLen = head.length() + fb->len + tail.length();
client.printf("POST /bot%s/sendPhoto HTTP/1.1\r\n", TG_BOT_TOKEN);
client.println("Host: api.telegram.org");
client.printf("Content-Length: %u\r\n", totalLen);
client.println("Content-Type: multipart/form-data; boundary=" + boundary);
client.println();
client.print(head);
const uint8_t* p = fb->buf;
size_t remaining = fb->len;
while (remaining > 0) {
size_t n = remaining > 1024 ? 1024 : remaining;
client.write(p, n);
p += n;
remaining -= n;
}
client.print(tail);
String resp;
const uint32_t start = millis();
while (client.connected() && millis() - start < 10000) {
while (client.available() && resp.length() < 600) resp += (char)client.read();
if (resp.indexOf("\"ok\":true") >= 0) break;
delay(10);
}
client.stop();
return resp.indexOf("\"ok\":true") >= 0;
}
bool sendSnapshot(const char* caption) {
camera_fb_t* fb = captureFresh();
if (!fb) { Serial.println("Capture failed"); return false; }
bool ok = sendPhotoTelegram(fb, caption);
esp_camera_fb_return(fb);
Serial.println(ok ? "Photo sent" : "Photo upload failed");
return ok;
}
// ---------- Helpers ----------
String timestamp() {
struct tm t;
if (!getLocalTime(&t, 100)) return "time not set";
char buf[24];
strftime(buf, sizeof(buf), "%d %b %H:%M:%S", &t);
return String(buf);
}
const char* stateText() {
switch (state) {
case DISARMED: return "Disarmed";
case ARMING: return "Arming...";
default: return "Armed";
}
}
void publishState() {
if (Blynk.connected()) Blynk.virtualWrite(V1, stateText());
}
void sendHealth() {
if (Blynk.connected()) Blynk.virtualWrite(V3, WiFi.RSSI());
}
// ---------- Blynk handlers ----------
BLYNK_CONNECTED() {
Blynk.syncVirtual(V0);
publishState();
}
BLYNK_WRITE(V0) { // arm / disarm switch
if (param.asInt() == 1) {
state = ARMING;
armingStartedAt = millis();
} else {
state = DISARMED;
}
publishState();
}
BLYNK_WRITE(V4) { // "photo now" button
if (param.asInt() == 1) snapshotRequested = true;
}
// ---------- Motion logic ----------
void raiseAlert() {
Serial.println("Motion detected while armed");
if (Blynk.connected()) {
Blynk.logEvent("motion_detected", "Motion detected by the ESP32-CAM");
Blynk.virtualWrite(V1, "ALERT");
Blynk.virtualWrite(V2, timestamp());
}
alertShown = true;
sendSnapshot("Motion detected");
}
void handleMotion() {
const bool motionNow = (digitalRead(PIR_PIN) == HIGH);
if (millis() < PIR_WARMUP_MS || state != ARMED) { // warm-up or not armed
prevMotion = motionNow;
return;
}
const bool rising = motionNow && !prevMotion;
prevMotion = motionNow;
if (!rising) return;
const uint32_t now = millis();
if (lastAlertAt != 0 && now - lastAlertAt < COOLDOWN_MS) return;
lastAlertAt = now;
raiseAlert();
}
// ---------- Connections ----------
void maintainConnections() {
static uint32_t lastTry = 0;
if (millis() - lastTry < 10000) return;
if (WiFi.status() != WL_CONNECTED) {
lastTry = millis();
WiFi.reconnect();
} else if (!Blynk.connected()) {
lastTry = millis();
Blynk.connect(3000);
}
}
void setup() {
Serial.begin(115200);
pinMode(PIR_PIN, INPUT);
pinMode(FLASH_PIN, OUTPUT);
digitalWrite(FLASH_PIN, LOW);
if (!initCamera()) {
Serial.println("Camera init failed - check power and the board selection");
delay(5000);
ESP.restart();
}
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
const uint32_t t0 = millis();
while (WiFi.status() != WL_CONNECTED && millis() - t0 < 20000) delay(250);
configTzTime(TZ_INFO, "pool.ntp.org", "time.google.com");
Blynk.config(BLYNK_AUTH_TOKEN);
timer.setInterval(15000L, sendHealth);
Serial.println("Ready");
}
void loop() {
maintainConnections();
if (Blynk.connected()) Blynk.run();
timer.run();
if (state == ARMING && millis() - armingStartedAt >= EXIT_DELAY_MS) {
state = ARMED;
prevMotion = (digitalRead(PIR_PIN) == HIGH);
publishState();
}
handleMotion();
if (snapshotRequested) {
snapshotRequested = false;
sendSnapshot("Snapshot requested");
}
if (alertShown && millis() - lastAlertAt > COOLDOWN_MS) {
alertShown = false;
publishState();
}
}How the Firmware Handles the Hard Parts
Rising-edge detection with a cooldown. A PIR output can stay HIGH for seconds or minutes. The code stores the previous reading and only acts on a LOW-to-HIGH change, and then ignores further triggers for 60 seconds. One person walking in produces one alert, not hundreds.
A fresh photo, not a stale one. The camera driver keeps frames buffered, so the first frame you grab after waking can be old and badly exposed. captureFresh() switches on the flash, discards one frame, waits briefly and then takes the one that is used.
Two independent paths. The Blynk event and the Telegram upload do not depend on each other. If Blynk is down, the photo still goes out. If the upload fails, the event has already been sent and the Serial Monitor shows the failure.
Non-blocking connection recovery. Instead of Blynk.begin(), which blocks until it connects, the sketch calls Blynk.config() and retries every ten seconds from loop(). The PIR logic and photo requests keep working through a Wi-Fi or cloud outage.
No work inside Blynk callbacks. The "photo now" button only sets a flag. The slow capture and upload happen in loop(), so the Blynk connection is never starved.
A note on TLS. setInsecure() skips certificate checking so the example works without extra setup, which means the connection is encrypted but the server's identity is not verified. For anything you depend on, load Telegram's certificate with setCACert() instead. The bot token is a credential, so never post it or commit it to a public repository.
Test in Layers
- Camera alone. Upload with the PIR disconnected and watch the Serial Monitor. You should see "Ready" with no camera error.
- Blynk connection. Confirm the device shows as online and the signal gauge updates every 15 seconds.
- Photo path. Press the Snapshot button in the app. A photo should arrive in Telegram within a few seconds.
- PIR alone. Add a temporary
Serial.println(digitalRead(PIR_PIN))and check that the value changes when you wave a hand, after the 30-second warm-up. - Arm and trigger. Switch the app switch on, wait out the exit delay until the status reads Armed, then walk into the PIR's view. You should receive a notification and a photo.
- Cooldown. Move again straight away and confirm there is no second alert for 60 seconds.
- Failure behaviour. Turn off your router briefly and confirm the board reconnects and keeps working. Reboot it and confirm it comes back disarmed or restores the switch state.
Placement Tips
Mount the PIR so movement crosses its field of view sideways, because PIR sensors detect crossing motion better than motion directly toward them. Keep it away from heaters, vents, direct sunlight and windows, which cause false alerts. Point the camera so the PIR and the lens cover the same area, and avoid pointing it at neighbours' property or public spaces.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| "Camera init failed" | Weak power, wrong board or PSRAM disabled | Use a 2 A supply and a capacitor, and select AI Thinker ESP32-CAM |
| Random resets or a brownout message | Power supply or cable too weak | Shorter thick cable, better supply, bulk capacitor |
| Upload fails with "Wrong boot mode" | GPIO 0 not tied to GND during upload | Add the jumper, press reset, then upload |
| Board will not run after upload | GPIO 0 jumper still in place | Remove it and press reset |
| Sketch too big | Wrong partition scheme | Choose Huge APP (3MB No OTA) |
| Blynk device stays offline | Wrong template ID, name or token, or no Wi-Fi | Re-copy the three values and check the SSID and password |
| No notification, but Serial shows an alert | Event code mismatch or notifications disabled | Match motion_detected exactly and enable notifications for the event |
| No photo in Telegram | Wrong bot token or chat ID, or you never messaged the bot | Message the bot first and recheck both values |
| Alerts as soon as it is armed | PIR still warming up, or armed too soon | Wait for the warm-up and keep the exit delay |
| Constant false alerts | Heater, sunlight or pets in view | Reposition and lower the sensitivity pot |
| Dark or green-tinted photos | Flash too close or exposure not settled | Keep the discard-and-wait capture, and increase the delay slightly |
Limits, Privacy and Next Steps
Treat this as a prototype. It has no battery backup, no local recording and no tamper detection, and it relies on your Wi-Fi, the Blynk cloud and Telegram all being available. Keep the camera inside your own property, tell people who share the space that it exists, and delete photos you no longer need. Never publish your tokens, and revoke a bot token with @BotFather if it is exposed.
To go further, read about PIR notifications with Blynk events, the Blynk 2.0 complete guide, and the related ESP32-CAM PIR Motion Detection Camera and ESP32-CAM Photo Capture with MicroSD Storage projects. For a local live view of the same camera, see the companion ESP32-CAM + Blynk Motion Snapshot Dashboard.
Official references: the Blynk documentation and the Telegram Bot API documentation.


