What You Will Build
This project gives an ESP32-CAM a proper control panel. On your home network, a password-protected web page shows a live view, a one-tap snapshot and the last photo taken when motion was detected. In the Blynk app you get the controls and status you would want on the go: a flash switch, a resolution selector, a restart button, the camera's address, signal strength, uptime and frame rate. When the PIR sensor sees movement, the board saves a snapshot in memory and sends a Blynk notification.
One design decision shapes the whole project, so it is worth stating plainly. Blynk is not used to carry video. It is a device-control and notification service, and there is no guarantee that a generic ESP32-CAM stream can be embedded in a Blynk dashboard. Instead, each tool does what it is good at: the camera serves its own images on your local network, and Blynk handles control, status and alerts. Splitting the roles this way also keeps your camera off the public internet.
You will also learn how to run an HTTP server and the Blynk connection on different CPU cores, so a long-running video stream never freezes your controls.
Architecture: Who Does What
| Task | Handled by | Network path |
|---|---|---|
| Live MJPEG view, snapshot, last motion photo | The ESP32-CAM's own web server (core 1) | Local network only, with a password |
| Flash switch, resolution, restart | Blynk app, running on core 0 | Blynk cloud |
| Status: signal, uptime, frame rate, last motion time | Blynk app | Blynk cloud |
| Motion notification | Blynk event | Blynk cloud |
The camera and its images never leave your network unless you choose to expose them. The Blynk cloud only ever sees small control and status messages.
Viewing From Outside the House
Do not forward port 80 on your router to the camera. A forwarded camera is found by internet scanners within hours. Use a VPN back into your home network instead, such as WireGuard on a router or Raspberry Pi, or a mesh VPN such as Tailscale. When the VPN is connected, your phone behaves as if it were on the home Wi-Fi, and the camera address from the Blynk dashboard just works.
Components
6 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.
Wiring and Pin Notes
Only the PIR needs wiring:
| HC-SR501 PIR | ESP32-CAM |
|---|---|
| VCC | 5V |
| GND | GND |
| OUT | GPIO 13 |
GPIO 13 is one of the few free header pins on the AI-Thinker board. Most of the others are used by the camera, the PSRAM, the microSD interface or the boot process, and GPIO 12 is a strapping pin that can stop the board booting if it is held HIGH. The six header pins are also ADC2 pins, so they cannot read analog values while Wi-Fi is on. The ESP32-CAM Pinout Guide has the full map.
On the PIR module, set the hold-time potentiometer to its minimum and leave the jumper on the repeat-trigger (H) position, because the firmware applies its own cooldown. The sensor needs 30 to 60 seconds after power-up to settle, and the firmware ignores it for the first 30 seconds.
To upload code, connect an FTDI adapter set to 3.3 V logic (GND, 5V, TX to U0R, RX to U0T), tie GPIO 0 to GND, press reset, upload, then remove the jumper and press reset again. See ESP32-CAM Programming: Getting Started if this is your first time.
⚠️ Warning
Video streaming is the hardest thing you can ask of an ESP32-CAM's power supply. Camera, Wi-Fi and flash together produce sharp current spikes. A weak USB port or thin cable causes brownout resets and "camera init failed" errors. Use a 5 V 2 A supply, a short thick cable and a 470 to 1000 µF capacitor across 5V and GND.
Set Up Blynk
Create a template with hardware ESP32 and connection WiFi, and add these datastreams:
| Pin | Name | Type | Widget |
|---|---|---|---|
| V0 | Flash LED | Integer 0 to 1 | Switch |
| V1 | Resolution | Integer 0 to 3 | Segmented switch: QVGA, VGA, SVGA, XGA |
| V2 | Restart | Integer 0 to 1 | Button |
| V3 | Last motion | String | Label |
| V4 | Camera address | String | Label |
| V5 | Wi-Fi signal | Integer, dBm | Gauge |
| V6 | Uptime | Integer, minutes | Label |
| V7 | Stream FPS | Integer | Label |
Under Events, create an event with the code motion_detected and enable notifications. The code is case-sensitive. Plans limit datastreams, events and notifications and these limits change, so if you are over a limit, drop V6 and V7 first.
Install the esp32 by Espressif Systems board package and the Blynk library (1.3.x). Select AI Thinker ESP32-CAM and the Huge APP (3MB No OTA/1MB SPIFFS) partition scheme. If a very new core gives compile errors with the Blynk library, try a core version Blynk is known to build on, such as 2.0.17.
The Firmware
Read these design points before the code, because they explain choices that look odd at first:
- Two cores. Blynk runs in its own task on core 0. The web server and camera work run in the normal
loop()on core 1. A long MJPEG stream blocksloop(), but Blynk keeps running, so controls and notifications still work during a stream. - Settings by flag. The Blynk task never touches the camera driver. It sets variables such as
requestedSizeIdxand the web side applies them, which avoids two tasks fighting over the sensor. - Motion by interrupt. The PIR pin sets a flag from an interrupt, and the web side handles it. If a stream is running, the motion snapshot is copied from the frame already in hand.
- One viewer at a time. The simple
WebServerlibrary serves one request at a time, so only one person can stream at once. That is a deliberate trade for simplicity. - A password on every page. Every route requires HTTP Basic authentication. Change the default password before you upload.
Set the Wi-Fi details, Blynk values and web password at the top, then upload.
// ESP32-CAM + Blynk motion snapshot dashboard
// Board: AI Thinker ESP32-CAM | Partition: Huge APP | Blynk library 1.3.x
#define BLYNK_TEMPLATE_ID "TMPLxxxxxxxx"
#define BLYNK_TEMPLATE_NAME "ESP32-CAM Dashboard"
#define BLYNK_AUTH_TOKEN "YOUR_BLYNK_AUTH_TOKEN"
#define BLYNK_PRINT Serial
#include <WiFi.h>
#include <WebServer.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* WEB_USER = "admin";
const char* WEB_PASS = "CHANGE_THIS_PASSWORD";
const char* TZ_INFO = "IST-5:30"; // change for your time zone
const uint8_t PIR_PIN = 13;
const uint8_t FLASH_PIN = 4;
const uint32_t PIR_WARMUP_MS = 30000;
const uint32_t MOTION_COOLDOWN_MS = 30000;
const uint32_t STREAM_MAX_MS = 300000; // each stream session ends after 5 minutes
const size_t LAST_SHOT_CAP = 256 * 1024;
// ---------- 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
const framesize_t SIZES[4] = { FRAMESIZE_QVGA, FRAMESIZE_VGA, FRAMESIZE_SVGA, FRAMESIZE_XGA };
WebServer server(80);
BlynkTimer timer;
uint8_t* lastShot = nullptr;
size_t lastShotLen = 0;
char lastMotionBuf[24] = "none";
uint32_t lastMotionAt = 0;
volatile bool pirTriggered = false;
volatile bool eventPending = false;
volatile bool restartRequested = false;
volatile int requestedSizeIdx = 1; // start at VGA
volatile int streamFps = 0;
int appliedSizeIdx = 1;
// ---------- Web page ----------
const char PAGE[] PROGMEM = R"rawliteral(
<!DOCTYPE html><html><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>ESP32-CAM</title>
<style>
body{font-family:system-ui,sans-serif;background:#0f1923;color:#e8eef5;margin:0;padding:1rem;text-align:center}
img{max-width:100%;border-radius:8px;background:#000}
button,a{color:#fff;background:#6366f1;border:0;border-radius:8px;padding:.6rem 1rem;margin:.3rem;
text-decoration:none;display:inline-block;font-size:1rem;cursor:pointer}
section{max-width:820px;margin:0 auto 1.5rem}
</style></head><body>
<section><h2>Live view</h2>
<img id="live" alt="Press Start"><br>
<button onclick="document.getElementById('live').src='/stream?'+Date.now()">Start</button>
<button onclick="document.getElementById('live').removeAttribute('src')">Stop</button>
<a href="/capture" target="_blank">Snapshot</a>
</section>
<section><h2>Last motion snapshot</h2>
<img id="last" src="/last.jpg" alt="No motion yet"><br>
<button onclick="document.getElementById('last').src='/last.jpg?'+Date.now()">Refresh</button>
</section>
</body></html>
)rawliteral";
// ---------- 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 = SIZES[1];
c.jpeg_quality = 12;
c.fb_count = 2;
c.fb_location = CAMERA_FB_IN_PSRAM;
c.grab_mode = CAMERA_GRAB_LATEST;
return esp_camera_init(&c) == ESP_OK;
}
void applyPending() { // runs on the web side only
const int want = requestedSizeIdx;
if (want != appliedSizeIdx && want >= 0 && want < 4) {
sensor_t* s = esp_camera_sensor_get();
if (s) { s->set_framesize(s, SIZES[want]); appliedSizeIdx = want; }
}
}
camera_fb_t* getFreshFrame() {
camera_fb_t* fb = esp_camera_fb_get(); // may be an old frame
if (fb) esp_camera_fb_return(fb);
return esp_camera_fb_get();
}
// ---------- Motion ----------
void IRAM_ATTR onPir() { pirTriggered = true; }
bool motionDue() {
if (!pirTriggered) return false;
pirTriggered = false;
if (millis() < PIR_WARMUP_MS) return false;
if (lastMotionAt != 0 && millis() - lastMotionAt < MOTION_COOLDOWN_MS) return false;
lastMotionAt = millis();
return true;
}
void storeSnapshot(camera_fb_t* fb) {
if (!lastShot || fb->len > LAST_SHOT_CAP) return;
memcpy(lastShot, fb->buf, fb->len);
lastShotLen = fb->len;
}
void recordMotion() {
struct tm t;
if (getLocalTime(&t, 50)) strftime(lastMotionBuf, sizeof(lastMotionBuf), "%d %b %H:%M:%S", &t);
else snprintf(lastMotionBuf, sizeof(lastMotionBuf), "uptime %lus", (unsigned long)(millis() / 1000));
eventPending = true; // set last: the Blynk task reads the buffer after this
}
// ---------- Web handlers ----------
bool authOk() {
if (server.authenticate(WEB_USER, WEB_PASS)) return true;
server.requestAuthentication();
return false;
}
void handleRoot() {
if (!authOk()) return;
server.send_P(200, "text/html", PAGE);
}
void handleCapture() {
if (!authOk()) return;
camera_fb_t* fb = getFreshFrame();
if (!fb) { server.send(503, "text/plain", "Camera busy"); return; }
server.sendHeader("Cache-Control", "no-store");
server.send_P(200, "image/jpeg", (const char*)fb->buf, fb->len);
esp_camera_fb_return(fb);
}
void handleLast() {
if (!authOk()) return;
if (lastShotLen == 0) { server.send(404, "text/plain", "No motion snapshot yet"); return; }
server.sendHeader("Cache-Control", "no-store");
server.send_P(200, "image/jpeg", (const char*)lastShot, lastShotLen);
}
void handleStream() {
if (!authOk()) return;
WiFiClient client = server.client();
client.print("HTTP/1.1 200 OK\r\n"
"Content-Type: multipart/x-mixed-replace; boundary=frame\r\n"
"Cache-Control: no-store\r\n"
"Connection: close\r\n\r\n");
const uint32_t started = millis();
uint32_t windowStart = started;
int frames = 0;
while (client.connected() && millis() - started < STREAM_MAX_MS) {
applyPending();
camera_fb_t* fb = esp_camera_fb_get();
if (!fb) break;
if (motionDue()) { storeSnapshot(fb); recordMotion(); } // reuse the frame we already have
client.printf("--frame\r\nContent-Type: image/jpeg\r\nContent-Length: %u\r\n\r\n", (unsigned)fb->len);
client.write(fb->buf, fb->len);
client.print("\r\n");
esp_camera_fb_return(fb);
frames++;
if (millis() - windowStart >= 1000) {
streamFps = frames;
frames = 0;
windowStart = millis();
}
}
streamFps = 0;
}
// ---------- Blynk (runs on core 0) ----------
BLYNK_CONNECTED() {
Blynk.syncVirtual(V0, V1);
Blynk.virtualWrite(V4, String("http://") + WiFi.localIP().toString() + "/");
}
BLYNK_WRITE(V0) {
digitalWrite(FLASH_PIN, param.asInt() ? HIGH : LOW);
}
BLYNK_WRITE(V1) {
requestedSizeIdx = constrain(param.asInt(), 0, 3);
}
BLYNK_WRITE(V2) {
if (param.asInt() == 1) restartRequested = true;
}
void publishStatus() {
if (!Blynk.connected()) return;
Blynk.virtualWrite(V5, WiFi.RSSI());
Blynk.virtualWrite(V6, (int)(millis() / 60000UL));
Blynk.virtualWrite(V7, (int)streamFps);
Blynk.virtualWrite(V3, lastMotionBuf);
}
void blynkTask(void*) {
uint32_t lastTry = 0;
for (;;) {
if (WiFi.status() == WL_CONNECTED) {
if (Blynk.connected()) {
Blynk.run();
if (eventPending) {
eventPending = false;
Blynk.logEvent("motion_detected", "Motion detected - snapshot saved");
Blynk.virtualWrite(V3, lastMotionBuf);
}
} else if (millis() - lastTry > 10000) {
lastTry = millis();
Blynk.connect(3000);
}
}
timer.run();
vTaskDelay(pdMS_TO_TICKS(10));
}
}
void setup() {
Serial.begin(115200);
pinMode(FLASH_PIN, OUTPUT);
digitalWrite(FLASH_PIN, LOW);
pinMode(PIR_PIN, INPUT);
if (!initCamera()) {
Serial.println("Camera init failed - check power and the board selection");
delay(5000);
ESP.restart();
}
lastShot = (uint8_t*)ps_malloc(LAST_SHOT_CAP);
WiFi.mode(WIFI_STA);
WiFi.setAutoReconnect(true);
WiFi.begin(WIFI_SSID, WIFI_PASS);
const uint32_t t0 = millis();
while (WiFi.status() != WL_CONNECTED && millis() - t0 < 20000) delay(250);
Serial.print("Dashboard: http://");
Serial.println(WiFi.localIP());
configTzTime(TZ_INFO, "pool.ntp.org", "time.google.com");
server.on("/", handleRoot);
server.on("/capture", handleCapture);
server.on("/stream", handleStream);
server.on("/last.jpg", handleLast);
server.begin();
attachInterrupt(digitalPinToInterrupt(PIR_PIN), onPir, RISING);
Blynk.config(BLYNK_AUTH_TOKEN);
timer.setInterval(10000L, publishStatus);
xTaskCreatePinnedToCore(blynkTask, "blynk", 8192, NULL, 1, NULL, 0);
}
void loop() {
server.handleClient();
applyPending();
if (motionDue()) {
camera_fb_t* fb = getFreshFrame();
if (fb) { storeSnapshot(fb); esp_camera_fb_return(fb); }
recordMotion();
}
if (restartRequested) {
delay(200);
ESP.restart();
}
delay(2);
}What the Code Does Under the Hood
The stream is a multipart response. MJPEG streaming is nothing more than a never-ending HTTP response in which each part is one JPEG, separated by a boundary line. The browser's <img> tag displays each part as it arrives, with no plugin needed.
Fresh frames for stills. With two frame buffers and the "grab latest" mode, the first frame you get can be old. getFreshFrame() discards one and returns the next.
Memory. The last-motion image is copied into a 256 KB buffer allocated in PSRAM, so the camera's own buffers are free to keep working. If a frame is bigger than the buffer, which can happen at the highest resolution, it is skipped instead of overflowing.
Resolution changes are safe. The Blynk task only records the request. The web side changes the sensor setting between frames, so two tasks never call the camera driver at the same time.
Realistic performance. Frame rate depends on resolution, JPEG quality, Wi-Fi signal and how busy your network is. Expect roughly the low twenties of frames per second at QVGA, and low double digits at VGA. SVGA and XGA are noticeably slower. The FPS value in Blynk lets you see what you actually get.
Cooldown. Motion is accepted at most every 30 seconds, so a person moving around does not overwrite the snapshot and flood your notifications.
Security Checklist
- Change the web password before uploading, and use a long unique one.
- HTTP Basic authentication over plain HTTP is not encrypted. Anyone on your Wi-Fi who can sniff traffic could read the credentials and the video. That is acceptable on a home network you control, and a good reason to keep the camera on a trusted or guest-isolated network, and to use a VPN for remote viewing.
- Never port-forward the camera. Use the VPN approach described above.
- Keep secrets out of screenshots and repositories, including the Blynk token, Wi-Fi password and web password. Rotate the Blynk token if it leaks.
- Think about privacy. Point the camera only at spaces you own or have permission to monitor, tell people who live with you, and keep the last-motion snapshot only as long as you need it. It is held in RAM and lost on reboot, which is a useful privacy property.
Test in Layers
- Camera alone. Upload and open the Serial Monitor. You should see the dashboard address and no camera error.
- Web page. Open the address in a browser, log in, press Start and confirm you see live video. Press Snapshot to see a still.
- Wrong password. Try a bad password and confirm every page and image is refused.
- Blynk. Confirm the device is online, the address label is correct, and signal and uptime update.
- Controls. Switch the flash on and off, change the resolution while streaming, and watch the image size change.
- Motion. Wait out the 30-second warm-up, walk past the PIR and confirm you get a notification and the last-motion image updates.
- Failure. Turn off the router and confirm the board reconnects and the dashboard comes back. Press Restart in Blynk and confirm the board reboots.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| "Camera init failed" | Weak power, wrong board or PSRAM disabled | 2 A supply, capacitor, select AI Thinker ESP32-CAM |
| Resets when streaming starts | Power dip from Wi-Fi and camera | Better supply and a short, thick cable |
| Stream is choppy | Weak Wi-Fi or resolution too high | Move closer, lower the resolution, or raise the JPEG quality number (a higher number means smaller files) |
| Page asks for a password again and again | Wrong credentials in the sketch | Match WEB_USER and WEB_PASS |
| Image shows "Press Start" only | Browser blocked or the stream ended | Press Start again. Sessions end after 5 minutes by design |
| Second viewer sees nothing | The server handles one request at a time | Close the first stream before opening another |
| No notification on motion | Event code mismatch or notifications off | Match motion_detected exactly and enable notifications |
| "No motion snapshot yet" | PIR still warming up, or the cooldown is active | Wait 30 seconds after boot and move again |
| Blynk online but no video | Different paths, as designed | Test the camera address on its own, from a device on the same network |
| Remote view fails | No VPN connected | Connect the VPN first. Do not forward the port |
| Sketch too big | Wrong partition scheme | Choose Huge APP (3MB No OTA) |
| Board will not boot | GPIO 12 pulled HIGH, or GPIO 0 still grounded | Keep GPIO 12 free and remove the programming jumper |
Next Steps
Good upgrades include saving each motion snapshot to a microSD card, and sending the snapshot to a private chat so you see it when away. Both are covered in the companion projects: ESP32-CAM Blynk Security System sends alert photos to Telegram, and ESP32-CAM Sensor Monitoring saves photos and readings to a card. For more on the camera board, see the ESP32-CAM Web Server Setup guide, PIR notifications with Blynk events and the Blynk 2.0 complete guide.
Official references: the Blynk documentation and the esp32-camera driver documentation.


