ESP32-CAM PIR Motion Detector with Photo Capture (saves to microSD card)

In this project, we’re going to make a motion sensor detector with photo capture using an ESP32-CAM. When your PIR sensor detects motion, it wakes up, takes a photo and saves it in the microSD card.

ESP32-CAM Motion Detection with Photo Capture (saves to microSD card)

This project is very similar with a previous one, but after so many requests, we added a PIR motion sensor to the circuit. So, when motion is detected a picture is taken and saved on the microSD card.

Other ESP32-CAM projects and tutorials:

We have a similar project using a Raspberry Pi and a camera module:

Watch the Video Tutorial

You can watch the video tutorial or continue reading for the complete project instructions.

Parts Required

For this project, you’ll need the following parts:

You can use the preceding links or go directly to to find all the parts for your projects at the best price!

Project Overview

ESP32-CAM Motion Detector with Photo Capture Project Overview

Here is a quick overview on how the project works.

  • The ESP32-CAM is in deep sleep mode with external wake up enabled.
  • When motion is detected, the PIR motion sensor sends a signal to wake up the ESP32.
  • The ESP32-CAM takes a photo and saves it on the microSD card.
  • It goes back to deep sleep mode until a new signal from the PIR motion sensor is received.

Recommended reading: ESP32 Deep Sleep with Arduino IDE and Wake Up Sources

Formatting MicroSD Card

The first thing we recommend doing is formatting your microSD card. You can use the Windows formatter tool or any other microSD formatter software.

1. Insert the microSD card in your computer. Go to My Computer and right click in the SD card. Select Format as shown in figure below.

Formatting your microSD card Windows

2. A new window pops up. Select FAT32, press Start to initialize the formatting process and follow the onscreen instructions.

Formatting your microSD card Windows

Note: according to the product specifications, the ESP32-CAM should only support 4 GB SD cards. However, we’ve tested with 16 GB SD card and it works well.

Installing the ESP32 add-on

We’ll program the ESP32 board using Arduino IDE. So, you need the Arduino IDE installed as well as the ESP32 add-on:

ESP32-CAM Take Photo with PIR Sketch

Copy the following code to your Arduino IDE.

  Rui Santos
  Complete project details at
   - Select Board "AI Thinker ESP32-CAM"
   - GPIO 0 must be connected to GND to upload a sketch
   - After connecting GPIO 0 to GND, press the ESP32-CAM on-board RESET button to put your board in flashing mode
  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.
  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
#include "esp_camera.h"
#include "Arduino.h"
#include "FS.h"                // SD Card ESP32
#include "SD_MMC.h"            // SD Card ESP32
#include "soc/soc.h"           // Disable brownour problems
#include "soc/rtc_cntl_reg.h"  // Disable brownour problems
#include "driver/rtc_io.h"
#include <EEPROM.h>            // read and write from flash memory
// define the number of bytes you want to access
#define EEPROM_SIZE 1
RTC_DATA_ATTR int bootCount = 0;

// Pin definition for CAMERA_MODEL_AI_THINKER
#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
int pictureNumber = 0;
void setup() {
  WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector
  camera_config_t config;
  config.ledc_channel = LEDC_CHANNEL_0;
  config.ledc_timer = LEDC_TIMER_0;
  config.pin_d0 = Y2_GPIO_NUM;
  config.pin_d1 = Y3_GPIO_NUM;
  config.pin_d2 = Y4_GPIO_NUM;
  config.pin_d3 = Y5_GPIO_NUM;
  config.pin_d4 = Y6_GPIO_NUM;
  config.pin_d5 = Y7_GPIO_NUM;
  config.pin_d6 = Y8_GPIO_NUM;
  config.pin_d7 = Y9_GPIO_NUM;
  config.pin_xclk = XCLK_GPIO_NUM;
  config.pin_pclk = PCLK_GPIO_NUM;
  config.pin_vsync = VSYNC_GPIO_NUM;
  config.pin_href = HREF_GPIO_NUM;
  config.pin_sscb_sda = SIOD_GPIO_NUM;
  config.pin_sscb_scl = SIOC_GPIO_NUM;
  config.pin_pwdn = PWDN_GPIO_NUM;
  config.pin_reset = RESET_GPIO_NUM;
  config.xclk_freq_hz = 20000000;
  config.pixel_format = PIXFORMAT_JPEG;
  pinMode(4, INPUT);
  digitalWrite(4, LOW);
    config.jpeg_quality = 10;
    config.fb_count = 2;
  } else {
    config.frame_size = FRAMESIZE_SVGA;
    config.jpeg_quality = 12;
    config.fb_count = 1;
  // Init Camera
  esp_err_t err = esp_camera_init(&config);
  if (err != ESP_OK) {
    Serial.printf("Camera init failed with error 0x%x", err);
  Serial.println("Starting SD Card");
    Serial.println("SD Card Mount Failed");
  uint8_t cardType = SD_MMC.cardType();
  if(cardType == CARD_NONE){
    Serial.println("No SD Card attached");
  camera_fb_t * fb = NULL;
  // Take Picture with Camera
  fb = esp_camera_fb_get();  
  if(!fb) {
    Serial.println("Camera capture failed");
  // initialize EEPROM with predefined size
  pictureNumber = + 1;
  // Path where new picture will be saved in SD Card
  String path = "/picture" + String(pictureNumber) +".jpg";
  fs::FS &fs = SD_MMC;
  Serial.printf("Picture file name: %s\n", path.c_str());
  File file =, FILE_WRITE);
    Serial.println("Failed to open file in writing mode");
  else {
    file.write(fb->buf, fb->len); // payload (image), payload length
    Serial.printf("Saved file to path: %s\n", path.c_str());
    EEPROM.write(0, pictureNumber);
  // Turns off the ESP32-CAM white on-board LED (flash) connected to GPIO 4
  pinMode(4, OUTPUT);
  digitalWrite(4, LOW);

  esp_sleep_enable_ext0_wakeup(GPIO_NUM_13, 0);
  Serial.println("Going to sleep now");
  Serial.println("This will never be printed");
void loop() {

View raw code

This code is very similar to one of our previous ESP32-CAM projects, but it enables external wake up on GPIO 13.


To learn more about the code, go to the following project:

ESP32-CAM Upload Code

To upload code to the ESP32-CAM board, connect it to your computer using an FTDI programmer. Follow the next schematic diagram:

ESP32-CAM connected to an FTDI Programmer to upload program using Arduino IDE

Many FTDI programmers have a jumper that allows you to select 3.3V or 5V. Make sure the jumper is in the right place to select 5V.

Important: GPIO 0 needs to be connected to GND so that you’re able to upload code.

ESP32-CAMFTDI Programmer
5VVCC (5V)

To upload the code, follow the next steps:

1) Go to Tools > Board and select AI-Thinker ESP32-CAM.

2) Go to Tools > Port and select the COM port the ESP32 is connected to.

3) Then, click the upload button to upload the code.

4) When you start to see these dots on the debugging window as shown below, press the ESP32-CAM on-board RST button.

After a few seconds, the code should be successfully uploaded to your board.

Schematic Diagram

ESP32-CAM with PIR Motion Sensor Circuit Breadboard

Assemble all the parts as shown in the following schematic diagram.

ESP32-CAM with PIR Motion Sensor Circuit Diagram
Thanks to David Graff for sharing the schematic diagram for this project

If you prefer, you can follow the Fritzing diagram instead.

ESP32-CAM with PIR Motion Sensor Schematic Diagram Fritzing

To prevent problems during upload, we recommend assembling the circuit only after uploading the code.


After uploading de code and assembling the circuit, insert a formatted microSD card and apply power to your circuit – you can use a portable charger, for example.

Powering ESP32-CAM with powerbank

Then, press the reset (RST) button, and it should start working. When it detects motion, it turns on the flash, takes a photo and saves it on the microSD card.

ESP32-CAM takes photo when detects motion with PIR sensor

Experiment with this circuit several times to make sure that it is working. Then, insert the microSD card to your computer to see the captured photos.

ESP32-CAM takes photo when detects motion with PIR sensor photo demonstration

Here’s an example:

ESP32-CAM photo example captured

Now you can finish this project the way you want, you can either use a dummy camera and insert your ESP32-CAM with the PIR motion sensor, or you can build your own enclosure.

ESP32-CAM PIR Motion Detector with Photo Capture with fake dummy camera

You can also apply the concepts learned in this tutorial in your own projects.


If you’re getting any of the following errors, read our ESP32-CAM Troubleshooting Guide: Most Common Problems Fixed

  • Failed to connect to ESP32: Timed out waiting for packet header
  • Camera init failed with error 0x20001 or similar
  • Brownout detector or Guru meditation error
  • Sketch too big error – Wrong partition scheme selected
  • Board at COMX is not available – COM Port Not Selected
  • Psram error: GPIO isr service is not installed
  • Weak Wi-Fi Signal
  • No IP Address in Arduino IDE Serial Monitor
  • Can’t open web server
  • The image lags/shows lots of latency

Learn how to program and build 17 projects with the ESP32-CAM using Arduino IDE DOWNLOAD »

Learn how to program and build 17 projects with the ESP32-CAM using Arduino IDE DOWNLOAD »

Wrapping Up

We hope you’ve liked this project. For more ESP32-CAM projects you can subscribe to our newsletter. If you don’t have an ESP32-CAM yet, you can get one for approximately $6.

If there is any project you’d like to see with the ESP32-CAM or if you’d like to share your project with us, write a comment in the comment’s section below.

We have more projects and tutorials about the ESP32-CAM that you may like:

Thank you for reading.

Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

271 thoughts on “ESP32-CAM PIR Motion Detector with Photo Capture (saves to microSD card)”

      • Hello Sara
        can i combine sms and picture transmission by your ESP8266 Multisensor Shield with Node-RED project that uses mqtt?
        thanks vm
        areza alikhani

          • when i try to upload code this give me this errror (Sketch uses 452201 bytes (14%) of program storage space. Maximum is 3145728 bytes.
            Global variables use 28172 bytes (8%) of dynamic memory, leaving 299508 bytes for local variables. Maximum is 327680 bytes.
            Serial port COM3

            A fatal error occurred: Failed to connect to ESP32: No serial data received.
            For troubleshooting steps visit: )
            Failed uploading: uploading error: exit status 2

      • Hello Sara,
        I can not combine ESP32-CAM Take Photo and Display in Web Server project with the ESP32-CAM PIR Motion Detector with Photo Capture to capture and display a new photo when motion is detected.
        Help me please;

      • Hello Sara, i need your attention. can we combile both code, motion detector and send it on the firebase with multiple pictures? kindly guide me.
        Thanks in advance

    • Hi,
      That’s a really cool project !
      I’ve tried it but there was a problem.
      The camera doesn’t stop taking picutres.
      I turn the system on and it just takes pictures on its own every 3 seconds.
      Do you know what the problem could be ?

      Best Regards.

      • Hi.
        It’s probably because the PIR motion sensor is being triggered every 3 seconds. Double check the connections of the PIR motion sensor.
        To make sure the ESP32-CAM is working properly, you can try attaching a pushbutton instead of the PIR sensor and see if it works as expected.
        Also, check with a multimeter if the PIR motion sensor is working as expected.

        • Hi Sara, I had a problem where the wifi connected espcam would take random photos. I eventually found the wireless signals from the esp32 were interfering with the PIR. Placing the PIR a few mm further from the esp32cam resolved this. Might be a good tip for others who find erattic photo behaviour.

          • Can you comment on expected delay between when pic is taken and when email might arrive. I am seeing long 3-5 minute delays

          • Hi.
            Using a gmail account, it takes no more than 30 seconds to arrive to my email account.

          • I believe I am having an issue with the power supply I am using. Parallel 1865 batteries and using a step up converter to get 5 volts . Everything works when I use the 5 volt PS from my pc USB but I cant get a reliable working system using the set up converter. Probably getting high frequency interference for the convert.

          • Yes, I am getting the same issue, even when the camera is only connected to upload sketch. Just keeps taking pictures until I disconnect.

          • Try moving the PIR further away from the aerial of the esp32cam. I found the radio waves can create a false trigger on the PIR signal wire.

        • Hi;
          I’ve tried to disconnect the PIR signal wire … nevertheless it continued to take photo each 3 seconds.

        • Hi,
          I have the same issue.The camera doesn’t stop taking picutres.I connect the circuit exactly like you do,but when I tested the circuit with a multimeter, I found that the PIR was not receiving power input.

  1. Hi love all your articles, thought you mite like to do a project using the small e ink modules 1.5 inches type maybe thanks so much .

  2. Just curious why you are using the elaborate setup to pull the pin low with the PIR instead of just connecting it directly and pulling it high?

  3. Is it possible to use only the ESP32-CAM as a motion sensor to send an email when it detects motion? In my case, it won’t be asleep/need to wake up, it will be on power supply and on waiting for a client to connect to stream video.

    thank you. nice website.

    • Hi.
      I’m not sure if the ESP32-CAM is powerful enough to detect motion on its own (i’ve never tried it).
      Sending an image via email will be one of our next projects.

    • Yes, it is possible. I realized, with due limits, a motion detector without the aid of the PIR, but processing the images (frame). The purpose was didactic and not professional, but it works 🙂

    • The 2N3904 is a very generic small silicon NPN transistor being used as a switch. Almost any cheap silicon NPN transistor ought to work, since you’re not using it for audio or RF purposes. Amazon lists a bag of 200 of them for less than a nickel ($0.05) each

    • Any BC237, BC547, BC107 should work as you just use it for switch fully on and nothing special..

      BC547 should everyone have

      For more than 100 mA take BC337

          • Thanks Sara,
            I’m lousy with software and can’t see where in code the pit is enabled to wake up processor and take pic. Also I thought I read somewhere that there was a book that included code that combined the two sketches?

          • Thanks Sara,
            I’m lousy with software and can’t see where to put the wake up and sleep code from the motion/pic sketch
            in the email/pic sketch. Which I assume would trigger the picture. Also I thought I read somewhere that there was a book that included code that combined the two sketches?

          • Thanks Sara,

            I got the book, downloaded the code but keep getting compile error on this line:
            localtime_r(&result.timesstamp, &dt);

            Here is the error: (if I comment out the above line code compiles?)
            Arduino: 1.8.19 (Windows 10), Board: “AI Thinker ESP32-CAM, 240MHz (WiFi/BT), QIO, 40MHz”

            C:\Users\Ted\Documents\Arduino\email_on_motion_dec16a\email_on_motion_dec16a.ino: In function ‘void smtpCallback(SMTP_Status)’:

            email_on_motion_dec16a:376:27: error: ‘SMTP_Result {aka struct esp_mail_smtp_send_status_t}’ has no member named ‘timesstamp’

            localtime_r(&result.timesstamp, &dt);


            Multiple libraries were found for “SD.h”

            Used: C:\Users\Ted\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.6\libraries\SD

            Not used: C:\Program Files (x86)\Arduino\libraries\SD

            Multiple libraries were found for “WiFi.h”

            Used: C:\Users\Ted\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.6\libraries\WiFi

            Not used: C:\Program Files (x86)\Arduino\libraries\WiFi

            Multiple libraries were found for “ESPAsyncWebServer.h”

            Used: C:\Users\Ted\Documents\Arduino\libraries\ESPAsyncWebServer

            Not used: C:\Users\Ted\Documents\Arduino\libraries\ESPAsyncWebServer-master

            exit status 1

            ‘SMTP_Result {aka struct esp_mail_smtp_send_status_t}’ has no member named ‘timesstamp’

            This report would have more information with
            “Show verbose output during compilation”
            option enabled in File -> Preferences.

  4. Hello,
    Is it possible to change the code because I will not be using PIR sensor. Im thinking if it is possible that the esp32 can be made to automatically take pictures once it is turn on. and take pictures every 2 seconds. What do I need to change in the Codes. thanks

  5. Hi, great article.

    Question: is it possible in this esp32 board that you plug in directly an e-ink raw display like WaveShare and drive it with the esp-32?

    • Hi Nik.
      Many of the pins exposed in this ESP32 board are being used either by the camera or by the microSD card slot.
      So, it can be very difficult and tricky to setup a display like that with this ESP32-CAM.
      (I’m not saying it is not possible, but it should be very tricky).

  6. Hi there, i am a newbie. The article it is just the Top.
    I have this problem:
    /esp-who/examples/single_chip/esp32-camera-screen/main/app_main.cpp:41:20: fatal error: dl_lib.h: No such file or directory
    i just comented the:
    //#include “dl_lib.h”
    and it work ok.
    Any idea?
    And it is possible to disable the flash light? Thnx.

  7. I can upload the sketch OK but cannot get the camera to work. Just grounding GPIO13 should cause the flash and camera to record a photo but nothing happens. Do you think I have got a faulty ESP32-CAM board?

  8. Just thinking about it, to wake up from deep sleep your code indicates that the pin is to be turned low by the PIR when movement is detected. But for this to work it will need an external pullup resistor so that it is normally high. When movement is detected by the PIR it will then pull this pin low and wake it up from deep sleep.
    esp_sleep_enable_ext0_wakeup(GPIO_NUM_13, 0);
    The pullup resistor would need to connect to 3.3V and not 5V.

    • The U0R and U0T are the U(ART)0R(X) and U(ART)0T(X) ports/pins on the ESP32. The ESP32 also has a UART1 (GPIO9/10, neither of which are broken out) and a UART2 (GPIO 16/17 but only GIPO16/RX2 is broken out.)

      • Hi Micro, if I know that the esp32 has several serial ports, but my question is about the esp32 cam, I want to know if it has more serial ports because seeing the data sheet says it only has one UOT and one UOR is why my doubt.

        Also that you recommend me to connect with a sim800l and send commands at from esp32 cam 🙂

        Thanks in advance 🙂

  9. in the beginning i had problem compiling the code but after reading in the comment section about the l.lib.h that can be commented,i did that and uploaded the code and is working perfect now.thank you guys,i appreciated it.regards.

    • Just comment out that library and you’re ready to go… It was already explained in some other comments and even one above yours 😉

  10. So if I understand correctly , there is nothing in the code that inhibits flash for this project? I really would like to set it up on a warehouse but I need it without flash
    Thanks again for all you guys do!

  11. Hi guys,
    Trying to run this ESP-Cam motion sensor app. On compile, I get “dl_lib.h No such file or directory”. Your first web server app works fine. Obviously, I’m missing a library or two.
    Where do you reference these libraries?

  12. Hi Sara and Rui,

    Can I use the PIR Motion Sensor (HC-SR501) in this project?

    If I can use it, do I have to modify the circuit, or the code?


  13. The ESP32 doesn’t stay in sleep mode. Therefore I’m getting numerous photos saved to the SD card because the code is automatically resetting again.
    Would this be because the PIR is constantly on LOW and so PIN 13 is always 0. I have kept very still but it goes round again and takes and saves a photo.

  14. Solved. It was a question of a reliable constant power supply. So, instead of using the laptop or a mains 5v adapter plug to power the device I used a YuRobot 545043 breadboard power supply fixed to a 1/4 size (420 points) breadboard. It now works smoothly at a constant 5v and without any glitches. I’ve yet to see how long the 9v battery will last though!
    Excellent sketch. I’ve also got it to send me email with photo attachment.

    • Hi Malcom.
      Thanks for sharing that.
      Can you tell me what approach did you use to send the photo to your email?

      • Hi Sara & Kilo
        You can get a good idea how to do this with :

        Obviously you will need to do a bit of tweaking to suit your own requirements.

        Let me know if you get stuck and I’ll see if I can help.

    • Yes.
      You can use GPIO 16 por example to attach the button (I’ve tested it and it works well with that pin).
      Then, you can simply check if the button was pressed and take a photo if that is the case.
      buttonState = digitalRead(buttonPin);
      if (buttonState==HIGH){
      (code to take a photo)

  15. Wow, Thank You both for your time, expertise and effort in helping us all out with this great hobby of ours. Please keep up the great work!!!
    From BC, Canada

  16. Hey Guys,
    I’m running this code on two AI Thinker ESP-32-Cam modules. Both systems run fine for awhile, taking pictures, storing pics, etc but then error-out when they come out of sleep. i.e.
    Saved file to path: /picture157.jpg
    Going to sleep now
    ets Jun 8 2016 00:22:57

    rst:0x5 (DEEPSLEEP_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    configsip: 0, SPIWP:0xee
    mode:DIO, clock div:1
    ho 0 tail 12 room 4
    ho 0 tail 12 room 4
    entry 0x400806b8
    Starting SD Card
    Picture file name: /picture158.jpg
    Saved file to path: /picture158.jpg
    Going to sleep now
    ets Jun 8 2016 00:22:57

    rst:0x5 (DEEPSLEEP_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    configsip: 0, SPIWP:0xee
    mode:DIO, clock div:1
    ho 0 tail 12 room 4
    ho 0 tail 12 room 4
    entry 0x400806b8
    [E][camera.c:1049] camera_probe(): Detected camera not supported.
    [E][camera.c:1249] esp_camera_init(): Camera probe failed with error 0x20004

    This happens on both systems. Anything similar happening for anyone else??

  17. I have mase this project. For a while I kept getting an error about waiting for VSync when I pressed the reset button. Eventually I discovered that there are at least two common versions of the camera and I had one where the pin allocations for VSYNC and VLCK were reversed from those in your code. When I set VSYNC to 22 and VLCK to 25 this problem disapeared. However I now have a different problem that has me stumped.
    I get this message on the serial monitor.
    Starting SD Card
    Guru Meditation Error: Core 1 panic’ed (Interrupt wdt timeout on CPU1)
    Core 1 register dump:
    PC : 0x40083e9c PS : 0x00060034 A0 : 0x80082df5 A1 : 0x3ffbe770
    A2 : 0x00000000 A3 : 0x3f400f74 A4 : 0x800df868 A5 : 0x3ffb1e80
    A6 : 0x00000003 A7 : 0x3ffc0ae0 A8 : 0x00000002 A9 : 0x3ffb843c
    A10 : 0x00000000 A11 : 0x00000080 A12 : 0x000b87c8 A13 : 0x3ffb1e60
    A14 : 0x00000000 A15 : 0x00000000 SAR : 0x00000016 EXCCAUSE: 0x00000006
    EXCVADDR: 0x00000000 LBEG : 0x4000c46c LEND : 0x4000c477 LCOUNT : 0x00000000
    Core 1 was running in ISR context:
    EPC1 : 0x400e00f1 EPC2 : 0x00000000 EPC3 : 0x00000000 EPC4 : 0x40083e9c

    Backtrace: 0x40083e9c:0x3ffbe770 0x40082df2:0x3ffbe7a0 0x40083411:0x3ffbe7c0 0x400e00ee:0x3ffb1ec0 0x400d1b9e:0x3ffb1ef0 0x400d3233:0x3ffb1fb0 0x4008bcd5:0x3ffb1fd0

    Core 0 register dump:
    PC : 0x400feede PS : 0x00060134 A0 : 0x800e6812 A1 : 0x3ffbc020
    A2 : 0x00000000 A3 : 0x00000001 A4 : 0x00000000 A5 : 0x00000001
    A6 : 0x00060120 A7 : 0x00000000 A8 : 0x800ea756 A9 : 0x3ffbbff0
    A10 : 0x00000000 A11 : 0x40089d48 A12 : 0x00060120 A13 : 0x3ffbb6c0
    A14 : 0x00000000 A15 : 0x3ffbbd20 SAR : 0x00000000 EXCCAUSE: 0x00000006
    EXCVADDR: 0x00000000 LBEG : 0x00000000 LEND : 0x00000000 LCOUNT : 0x00000000

    Backtrace: 0x400feede:0x3ffbc020 0x400e680f:0x3ffbc040 0x4008dbd5:0x3ffbc060 0x4008bcd5:0x3ffbc080

    ets Jun 8 2016 00:22:57
    This goes on and on over and over.
    Looks like the watchdog timer is rebooting.
    Any help would be great.

  18. Hello, I like your tutorials. I request to make the tutorial to Email the Pictures clicked by the CAM module after detecting the motion by PIR sensor.

  19. The schematic doesn’t appear to match the fritzing diagram. The 5 volt + goes to the 5V pin on the ESP32 on the diagram, but the schematic show it going to VCC, which I think is correct.

  20. Hello, I’m doing a rush school project right now and might want to ask if it’s possible to add something on your project, probably a relay that will turn on light and make an active buzzer ring whenever there is a motion detected from the PIR using only the esp32cam?

  21. There have been a few questions regarding the flash LED on the ESP32-CAM board and this should help clarify the LED activity. The LED is controlled by GPIO4 which is also used as DATA1 on the SD card. Reading and writing to the SD card will cause the LED to glow brightly. In this program the LED is NOT lit when the picture is taken, so it will not help with the exposure. It IS brightly lit when the frame buffer is written to the SD card, immediately after the picture is taken. This may lead one to incorrectly think that it is a flash to illuminate the subject. When using the SD card, you have no control over the LED. Programs that do not use the SD card may control the LED by setting GPIO4 high or low. If LED illumination is needed for proper exposure, this program could be modified to initialize the SD card after the picture is taken. This would allow you to use GPIO4 to illuminate the LED before taking the picture.

  22. Very awesome ! it works with me…than you very much! 🙂

    but I have one question…Is there any way I can remove the flash light? from the code?

  23. Hi Sara,
    it´s a very good Projekt.
    Sorry for my bad english. I am from Germany.
    I need to take a Picture and save ist to sd card in the VoidLoop.
    Operation with power adapter then i dont need the sleep mode.
    In my Projekt works the ESP32 Cam Modul with WIFI and Blutooth thats why not Sleep Mode.
    Can you tell me what´s code i need only for make a Picture and save to sd card.
    I try it but i becom some Error over Variable not declared in this scope.
    My Problem is, i works not so long with Arduino.


    • Hi.
      You can use the following function to take and save a photo. Copy that function to the end of your code.

      void takeSavePhoto(String path){
      // Take Picture with Camera
      camera_fb_t * fb = esp_camera_fb_get();
      if(!fb) {
      Serial.println(“Camera capture failed”);

      // Save picture to microSD card
      fs::FS &fs = SD_MMC;
      File file =, FILE_WRITE);
      Serial.println(“Failed to open file in writing mode”);
      else {
      file.write(fb->buf, fb->len); // payload (image), payload length
      Serial.printf(“Saved file to path: %s\n”, path.c_str());

      //return the frame buffer back to the driver for reuse

      Then, in the loop() you can call it as follows:

      String path = “/picture” + String(pictureNumber) +”.jpg”;
      Serial.printf(“Picture file name: %s\n”, path.c_str());

      // Take and Save Photo

      Make sure you have the microSD card initialized.

      I hope this helps.


  24. If I don’t use the sd card, can I use:
    GPIO 12, 13, 14, 15 for ADC input?
    and GPIO 2, 16 for I2C communication?

    Or are any of these pins also used by the camera?

  25. Hi Rui,
    Can the ESP32-CAM be programmed to be a streaming web server plus being able to detect motion, which then will make it send a picture to email?

    • Hi.
      It should be possible. However I’m not sure if the ESP32-CAM is able to stream and detect motion with interrupts at the same time.
      Maybe you can have the two features on your project, but not at the same time. It can only detect montion if it is not streaming.
      However, I haven’t tried it.

  26. Hello,

    In building the motion triggered ESP32 project, I see that in order to start the
    program a reset is needed. Is there any way to set up an external reset switch?
    Being that the reset on the ESP32 pcb is very hard to access?

    Thank you,

  27. Currently you store the image on a SDcard or SPIFFs.
    The problem is that these wear, you don’t have unlimited write cycles.

    But you can send the image data without storing it.
    smtpData.addAttachData(FILE_PHOTO, “image/jpg”, (uint8_t*) fb->buf, (size_t) fb->len );

    I do this directly in the sendPhoto(); function.
    Tested, works.

  28. This unit works fine but is far too sensitive and takes lots of photos without showing an animal or human. I think it operates when the wind blows branches thus triggering the camera. Is there a way of making it less sensitive such as a resistive divider between the PIR and the transistor or a partial screen in front of the PIR to reduce its sensitivity?

  29. Is there a way/project to add timestamp to the photos? Even if it’s in the file name, doesn’t have to be on the image or anything. The reason I’m asking is because we use these cameras in wildlife monitoring and it would be really great to know when the animal walked by and on what day.

  30. Hello,
    Thanks for the tutorial, it is very good.

    I managed to take a picture when it detects movement and upload it to the server, finally I used a PIR sensor, a relay and an arduino nano.

    When it detects movement, it sends a signal to a relay that operates the camera for 30 seconds. The same thing happened to me as the person who made a comment above, once movement was detected, I was constantly sending photos to the server. With the relay active the camera for 30 seconds and only sends the photos during this time interval.

    The problem I have is that the photo does not have much quality, it comes out dark and very greenish.

    Do you know how the quality of photography can be improved?

    Thanks in advance.

  31. So great project,
    Could we code the ESP32 Camera as ftp server to view photos that were captured over Wifi @Sara Santos?
    Many thanks

  32. I did “#define EEPROM SIZE 256” and it runs cell EEPROM 256 instead of starting at 0. it overwrites all 256 images.
    I want the value of EEPROM to be 0 -255.
    Please help me!

    • Value 255 is factory preset. It means that this byte has not been used yet.

      The solution for more than 256 pictures that worked for me was using all EEPROM_SIZE=4000 bytes while just using 255 of 256 bits per byte. Bit value 255 generally means that the byte location has never been used so I never use this value. I used values 0…254 only. Like this a 4KB EEPROM can cover 25540000.2MB = ~200GB of 200KB photos.

      Those who do not believe that the bytes have the value 255 from the factory can try it themselves:

      Now you could write a loop that reads through the bytes like the following: Byte 0: 254, byte 1: 254, …, …, byte X: a) 0…254 (=last picture) OR b) 255 (byte location X has never been used!).

      Let’s say X is byte location 1 and you read a byte value of 254. This means the previous pictureNumber was 254+1+254+1=510. -> pictureNumberNew: 511.

      But if X was byte location 1 and you read a byte value of 255, then this means it doesn’t count because bytes with value 255 are unused. So your previous pictureNumber was 254+1=255. -> pictureNumberNew: 256.

  33. thank you for your advise.

    Hello, I am korean student.
    I learn about arduino IDE.

    Can I change motion sensor to pressure sensor?

    I wonder that if pressure sensor catch the pressure change, cam take a picture.

    How can I change source code?

    thank you.

    • Hi Lee.
      If your pressure sensor is analog, you need to read the sensor in the loop() and add an if statement to check whether the values have changed significantly.
      If they have changed, add the lines of code to take a picture. The lines after this comment:
      // Take Picture with Camera
      Don’t forget to remove the lines of code for the PIR sensor and for deep sleep.

      • Thank you for your adivce!

        Can I ask more question?

        If pressure sensor is digital, can we use this source code?

        For example,
        When pressure is detected, a picture is taken and the sensor is triggered.
        At this point, we use digital signals. The signal is detected. No.

        We just change PIR sensor to pressure sensor.

        thank you.

  34. Hi! really a nice Project! But like Nate and Jeffrey from 2019 I want to know why use the transistor… Is not more Easy to read directly the HIGH from the sensor?
    Maybe is needed for awake from deepsleep? Thanks!

  35. hello, could gpio13 still be used even though the microSD card is used? in your ai-thinker pinout tutorial it said that gpio13 is connected to data3 pin of the microSD card

  36. Greetings from Brazil!!
    Congratulations on your tutorials are great, I use several examples of you guys!!
    I’m having trouble with the circuit, he can’t take a picture.
    When I run this tutorial, ” ” works perfectly.
    When I run the PIR alone with a led it also works perfectly.
    But when I run this tutorial it doesn’t work, I’ve tried to trigger the GPIO13 directly with 3.3V and it still doesn’t work.
    I’ve used several external sources and it didn’t work.
    Would there be any solution?

    • I am having the same issue. The camera saves an image, flash triggers. Camera goes into deep sleep. PIR does not respond. When I test the PIR in a basic led circuit the led lights up – so I know the PIR works but not in this sketch. No idea why (I am a newbie).

  37. Hello Sara,
    thank you both for the great projects. I am currently looking at the projects from the e-book for the ESP32 cam and building them.
    But with this project I have a problem: The cam takes a photo every 5 seconds even if there was no movement.
    What could this be? I use your sketch and wiring from the eBokk without changes.

    Greetings and thanks Ulli

  38. Hallo to both of you,
    my question is simple. Why do you need a inverter Transistor ?. I modified th following line:

    esp_sleep_enable_exto_wakeup(GPIO_NUM_13,1); // instead of Zero
    It works ! Is there any reason for the use of the inverter ?


    Ernst Helmut

  39. Hi Sara and Rui,

    First, thank you so much for all the tutorials. They are extremely helpful!

    I’m quite new at programming the ESP32 and am super confused regarding the PIR and transistor. I can see that the transistor is amplifying and inverting the PIR output, but I can’t figure out why.

    I wanted to use this part of your circuit for other purposes and have been turning an LED on and off via the PIR as a proof of concept. Of course, it kept turning on when there is no motion and off on motion. I couldn’t figure out what was going wrong and duplicated the circuit several times before doing the obvious and getting out a multimeter.

    Is there any reason I shouldn’t take the transistor out and just use the output of the PIR directly into the ESP32 input pin?

    Thanks again for all your great projects!


    • Hi.
      You can remove the transistor and instead of the following line:
      esp_sleep_enable_ext0_wakeup(GPIO_NUM_13, 0);
      You should have
      esp_sleep_enable_ext0_wakeup(GPIO_NUM_13, 1);

  40. Dear.
    First I want to praise your projects. I learned a lot from them. I’ve been searching the internet for a long time, but nowhere can I find a project or program for the ESP32 CAM that would take a photo after receiving a signal from the motion detector and saving the image to an SD card, with the addition of allowing me to connect to an ESP32CAM and download pictures from SD card when I’m around. So just upgrade to your existing project: “ESP32-CAM PIR Motion Detector with Photo Capture (saves to microSD card)”. So this is a cottage where there is no wifi signal, so I would like ESP32CAM to take pictures if someone hangs around the cottage, and when I come I can look at the pictures on the SD card without taking it out of ESP32CAM. It means viewing or downloading content from the SD card via http or ftp. If you can help me with the program …
    Thank you in advance.

  41. Hey.
    How to turn off the flash LED.
    add this
    int inputPin = 12;
    and in void setup this
    pinMode (inputPin, INPUT_PULLUP);
    and add this
    pinMode (4, OUTPUT);
    digitalWrite (4, LOW);
    rtc_gpio_hold_dis (GPIO_NUM_4);
    config.pixel_format = PIXFORMAT_JPEG;
    and change this
    if (! SD_MMC.begin ()) {
    if (! SD_MMC.begin (“/ sdcard”, true)) {
    and set this to pin 12
    esp_sleep_enable_ext0_wakeup (GPIO_NUM_12, 0);

    if you get vsync error change this to larger number
    config.jpeg_quality = 10;

      • Awesome outcome JB!
        Just curious why you indicate to change pin 13 to 12?
        Adding your code on the original pin13 works great, too!

        • I’m not sure anymore.
          I think it has something to do with the SD card and that I use (ext0_wakeup (GPIO_NUM_12, 1) high signal,
          with the PIR Motion Sensor HC-SR501.

  42. Thanks for the help, but this is a little too complicated for me anyway. I’m looking for something simpler. A simple program for transferring data from an SD card.

  43. hey Rui and Sara.
    thanks for another inspiring project.
    A tip. If you use the camera in a dark environment.
    It works well with a standalone LED lamp with its own PIR sensor, at 10 – 20 Watts.

    By the way, I changed the code a bit,
    to avoid the cam module hanging,
    when I occasionally get a camera error.
    in this way the camera module goes into sleep even if there are errors.
    here are my changes if anyone is interested.

    add this at the beginning of the sketch
    long eventTimeout = (long) millis () + 2000;

    and add this at the very end of the setup.
    eventTimeout = (long) millis () + 2000;

    and put the sleep routine in the void loop section like this
    void loop () {
    if ((long) millis () – eventTimeout> = 0) {
    Serial.println (“Going to sleep now”);
    // Turns off the ESP32-CAM white on-board LED (flash) connected to GPIO 4
    pinMode (4, OUTPUT);
    digitalWrite (4, LOW);
    rtc_gpio_hold_en (GPIO_NUM_4);
    esp_sleep_enable_ext0_wakeup (GPIO_NUM_13, 0);
    esp_deep_sleep_start ();
    Serial.println (“This will never be printed”);


  44. Hi
    If you do not like writing to the EEprom every time a picture is taken.
    It can be avoided by changing the code as below.
    then writing to the EEprom only happens on reset and powerup.
    This is done by adding an extra counter, count.
    Maybe someone knows a better way to do it,
    but this is the best I could achieve right now.

    Add this after the include section.
    RTC_DATA_ATTR unsigned short int pictureNumber = 0;
    static RTC_NOINIT_ATTR unsigned short int count = 0;

    remove this.
    int pictureNumber = 0;

    Add this

    Add this
    if (pictureNumber == 0) {
    count = (0);
    if (count >= 99) {
    EEPROM.write (0,0);
    EEPROM.commit ();
    else {
    EEPROM.write (0, count + 1);
    EEPROM.commit ();
    config.pixel_format = PIXFORMAT_JPEG;

    Replace this
    // initialize EEPROM with predefined size
    pictureNumber = (0) + 1;
    with this
    pictureNumber = pictureNumber + 1;

    Replace this
    String path = “/ picture” + String (pictureNumber) + “. Jpg”;
    with this
    String path = “/ pic_” + String (count) + “-” + String (pictureNumber) + “. Jpg”;

    and finally remove
    EEPROM.write (0, pictureNumber);
    EEPROM.commit ();
    before this
    file.close ();
    esp_camera_fb_return (fb);
    delay (1000);

  45. Hi,

    I try since a certian time now a bit more into ESP32 Cams. Again great projects here Sara and Rui. Thanks for sharing your knowledge.

    The hint with the:
    esp_sleep_enable_ext0_wakeup(GPIO_NUM_13, 1);
    was reducing the cabeling significantly; – and as I was struggeling to find an 2N3904 (I tried a BC547, – but I think I did a mistake)- this change in the scetch did help significantly.

    Eventually just put it into your tutorial as an alternative specifically for beginners and/or non electronic freaks (like me).

    Else you are realy great.

    Greetings for the South of Germany.

    Stay healthy.


  46. I would like to use the cam to take pictures maybe every 10 minutes or so automatically. I know you have covered that already, but I would like to add having the PIR take a picture if motion is detected. So, basically auto picture, but add PIR motion detection too.

    How would I go about doing that?

    Thanks for the info so far!

  47. Hi finally got Arduino IDE to work on my Linux machine. Thanks for a great little tutorial!
    I would like to use in place of the PIR a microwave module (RCWL-0516) which has a TTL output that goes from low to high when triggered. As this module already has a TTL output could I not change the code from GPIO_NUM_13, 0 to 255. or is it not that easy.
    Thanks for all your work.

    • Cancel my last request, I think I’ve worked out the curcit and realise that the output from the PIR is the same as that from the RCWL-0516. ie high when active and the esp32 needs to have the input pulled to 0v. So off to dig out my collection of transistors.

      Thanks for all the hard you do in setting up and maintaining the website.

  48. Hi Rui,
    I from the circuit I have connected emitter of 2N3904 to 5v instead of GND but the circuit is still working fine. How this is possible?

  49. I thought I had it this time and then I got this message when it failed…
    Arduino: 1.8.16 (Windows 10), Board: “AI Thinker ESP32-CAM, 240MHz (WiFi/BT), QIO, 80MHz”

    Sketch uses 424542 bytes (13%) of program storage space. Maximum is 3145728 bytes.

    Global variables use 18816 bytes (5%) of dynamic memory, leaving 308864 bytes for local variables. Maximum is 327680 bytes. v3.0-dev

    Serial port COM12


    Traceback (most recent call last):

    File “”, line 3682, in

    File “”, line 3675, in _main

    File “”, line 3330, in main

    File “”, line 512, in connect

    File “”, line 492, in _connect_attempt

    File “”, line 431, in sync

    File “”, line 369, in command

    File “”, line 332, in write

    File “site-packages\serial\”, line 323, in write

    serial.serialutil.SerialTimeoutException: Write timeout

    Failed to execute script esptool

    An error occurred while uploading the sketch

  50. Using this piece of code for a simple surveillance unit. Battery (18650) power with a solar powered battery charger. As my ESP32 unit (cheap chines AI thinker clone) sporadically has both problems with the camera init (dreaded 0x20003 error) as well as with SC card init I have moved the suspend code into a separate function so I can got into suspense and ignore those camera and SD card problems.

  51. Hi This is great!
    Thank you.

    What is this part of the code for?
    During the camera config. Why is it INPUT and not output if you are writing to it?

    pinMode(4, INPUT);
    digitalWrite(4, LOW);

    • I think that was supposed to be OUTPUT, not INPUT. But you can set a pin as INPUT and then force it HIGH or LOW by writing to it (many, if not all, AVR MCU’s like the ATMEGA or ATTINY ones will also allow that but you need to make sure there’s no pullup/pulldown either internal or external in most cases for it to work.) This can be useful when another part of the program is monitoring a GPIO and you simply want to force it to ignore it for a while or if you want it to come out of deep-sleep with a known level.

      See where it says:

      Enable gpio pad hold function.

      The gpio pad hold function works in both input and output modes, but must be output-capable gpios. If pad hold enabled: in output mode: the output level of the pad will be force locked and can not be changed. in input mode: the input value read will not change, regardless the changes of input signal.

      The state of digital gpio cannot be held during Deep-sleep, and it will resume the hold function when the chip wakes up from Deep-sleep. If the digital gpio also needs to be held during Deep-sleep, gpio_deep_sleep_hold_en should also be called.

      Power down or call gpio_hold_dis will disable this function.

      ESP_OK Success

      ESP_ERR_NOT_SUPPORTED Not support pad hold function

      gpio_num: GPIO number, only support output-capable GPIOs

      Disable gpio pad hold function.

      When the chip is woken up from Deep-sleep, the gpio will be set to the default mode, so, the gpio will output the default level if this function is called. If you don’t want the level changes, the gpio should be configured to a known state before this function is called. e.g. If you hold gpio18 high during Deep-sleep, after the chip is woken up and gpio_hold_dis is called, gpio18 will output low level(because gpio18 is input mode by default). If you don’t want this behavior, you should configure gpio18 as output mode and set it to hight level before calling gpio_hold_dis.

      ESP_OK Success

      ESP_ERR_NOT_SUPPORTED Not support pad hold function

      gpio_num: GPIO number, only support output-capable GPIOs

  52. Hi Rui, good code and thanks for the post!!!

    I’m a newbie on ESP32 CAMs. My goal is to make and save photos on cards commanded through another Arduino UNO board. How should I modify this circuit to achieve that? Do I need simply a direct output pin in Arduino to GPIO13 ESP32CAM pin, so a pulse HIGH-LOW-HIGH will trigger ESP32CAM reset, avoiding a transistor?

    Couldn’t ESP32CAM be powered through 3.3V? 5V are compulsory?

    • Hi.
      Yes, you can send a signal from the Arduino to trigger the ESP32-CAM to take and save a picture.
      You don’t necessarily need to use interrupts. You can use digitalRead as you would do using a pushbutton depending on the pulse you send from the Arduino.
      The ESP32-CAM sometimes works with 3.3V (or not). You have to test it for your scenario. But, for more stability, I recommend 5V.

  53. Just wondering if it would be possible to add a photoresistor to the set up and add code so that the flash only activates in low light?

  54. Have you thought about writing a tutorial for the ESP32CAM to do motion triggered video recording instead of photo capture? I love the tutorials it’s my first stop when trying to imagine the possibilities.

    • Hi.
      You would need an OV2640 camera for arduino (arducam) and a microSD card module.
      Then, you would need to define the right pins in the code and use libraries compatible with the Arduino.
      I never tried it, so I’m not sure if there are any other tricks.

  55. Hi
    Very well done.
    In the schematic picture you have a 5V supply for moition sensor but in Fritzing you use 3.3V.
    Please check.
    Why do you use a transistor for sensor signal?
    Have a good day.

  56. Bonjour Sara,
    Je n’ai pas de capteur PIR sous la main.
    Comment puis-je modifier le code pour utiliser un capteur a ultrasons HCsr04 un peu comme ici
    Merci pour votre aide!

  57. Hi Sara
    Now I have got the transistor 2N3904 and it works fine.
    But I did not yet understand the function of the transistor.
    Is the function a switch or an ampifier?
    Can you explain it for me?

    • Hi Sara
      The transistor is just a switch to pull the esp32 pin_13 down.
      By the way I get a dark greenish picture with all the projects and I am wondering what’s the problem with code? There is something wrong with camera setup in the code I guess!!

  58. Hello Sarah, I am grateful for your nice work. I have a project and I want to take a video, not a picture. What code do I change? I also want to replace the sensor with an ultrasound sensor. What is the method? Thank you in advance

  59. Hi Sara, thanks for the great job
    My photos with this and the rest of the esp32-cam related projects are dark and greenish?! Do you know the reason?

  60. Hii sara
    I got an error ”A fatal error occurred: Invalid head of packet (0x65)” after press the reset button while uploading the code. I had checked my connection many times. I made as same as schematic diagram. How can I solve this?

  61. Hello, I’m going to combine ESP32CAM with HC-SR501 PIR motion sensor.
    You can see my code here:
    I connected the Motion sensor output to pin number 12 or 13 directly(Is it possible to connect motion sensor output to esp32-cam directly?).
    but I got blinking led without any motion detected?
    where is the problem?

  62. Hi Sara
    Thanks for your great project!

    I have designed an instrument for my research project to collect some information from the environment. What I need is to take photo when a certain characteristic happens. Then my main board sends command signal to ESP-Cam and take a photo. Could you please help me with this. Can I directly wires NODEMCU pin to GPIO13 to wakeup the ESP-Cam?


  63. Hello Sara,

    the shutter lag – the delay between “wake up” and the first pic is for me too big.

    So, I tried to erase the lines for deep sleep, but now, it takes only one picture. What can I do?

    Thank you for the great work and support.


    • Hi.
      Instead of taking the picture in the setup(), check the state of the PIR sensor on the loop() and call the corresponding lines to take a picture when motion is detected.
      if motion
      then, take a picture
      Or you can use interrupts that will call a specific function automatically when motion is detected. To learn about interrupts, you can read:
      I hope this helps.

      • Hi Sara,
        thanks for the quick reply.

        I placed the lines after “// Take Picture with Camera” in the loop section, but now – the camera takes pictures all the time 🙂

        Which is the line for the PIR and do I have to change something? Sorry for my bad understanding of the programming language, perhaps I have too many projects parallel.

        • Hi.
          You need to check the PIR state before calling the functions that take pictures.
          To check the state of the PIR, you can simply use digitalRead and if statements and also some timers, or interrupts.

  64. Thanks for such a good project and description!
    I built this and it works great, but for some reason, after a short while, maybe 10 minutes or so, it just stops responding. So I reboot and all is well again but after a few minutes it stops. Perhaps it is just not waking up.

    There is plenty of room on the SD card, and nothing is moved so there is no shorting. I have never debugged an esp32 so I am wondering if you have any suggestions on what to look for. Thanks!

  65. Hello,
    Thanks for this project.

    I’m having some troubles trying to make it work.

    As soon as I power the PIR, the code loops again and again for some reason. I did the exact same thing as you. I’m having troubles figuring it our.

    I tried a code to just power a led via the motion sensor. Here’s what appears on the monitor, over and over again :

    “21:04:31.120 -> ets Jun 8 2016 00:22:57
    21:04:31.120 ->
    21:04:31.120 -> rst:0x5 (DEEPSLEEP_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    21:04:31.120 -> configsip: 0, SPIWP:0xee
    21:04:31.120 -> clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
    21:04:31.120 -> mode:DIO, clock div:1
    21:04:31.120 -> load:0x3fff0030,len:1184
    21:04:31.120 -> load:0x40078000,len:12812
    21:04:31.120 -> load:0x40080400,len:3032
    21:04:31.120 -> entry 0x400805e4
    21:04:33.128 ->
    21:04:33.128 -> BOOTED!
    21:04:33.128 -> Wakeup caused by external signal using RTC_IO
    21:04:33.128 -> LED on
    21:04:35.105 -> LED off

    same thing is happening with your code.

    Could you possibly know what’s the matter?

  66. Hi Firstly thanks for a great project I am going to use it as a basis for a trail camera. I do have a few observations,
    1) There is a discrepancy between the schematic and the Fritzing diagram the schematic has the PIR power coming from 5v, the other is 3.3v so if using 3.3v you need to check the spec. of the PIR to see if it will work.
    2) I have seen comments about it constantly taking picture, I had this at first but by adjusting the time delay on the SR-501 I am using to a greater interval it works fine. You need either a volt meter of a LED with resistor to check the output going to the transistor.
    3) The transistor can be any general purpose NPN or even an N channel FET, I am using a 2N7000.
    4) I see many comments about using the transistor and can it be avoided, as you made a comment about the exposed GPIO pins being used by the camera and also the SDcard reader, GPIO13 is used by HS2_DATA3 on the card reader with a 47K pullup to Vcc so the transistor when ON is pulling it down with a 10K resistor so the LOW is detected and wakes up the ESP32cam. However it still allows the pin to work for writing the photo to the card.

    Finally I would like to be able to turn off the flash when taking a photo but I assume I will have to delve into the esp_camera.h library to change this, has anybody done it already?

    Thanks again and keep up the great work.

    • Hi.
      I think it is better to use another ESP32 or another microcontroller to connect all those peripherals.
      The ESP32-CAM has a limited number of pins, and some of them are being used by other components like the microSD card.
      It might be difficult to put everything together on the ESP32-CAM (not impossible, but it might be a nightmare trying to understand which pins to use with the peripherals you’re using).

  67. Hi Sara,

    My SD card is connected, and when I reset it it recognizes it and takes a photo. However, after 1 or 2 photos it freezes and tells me that there is no SD card connected. Do you know why this could be happening?


  68. Any suggestions why most of the time I get the top half of the image, with the bottom half being blank.

    // Take Picture with Camera
    fb = esp_camera_fb_get();

    Would a short delay after the above help?


  69. Thank you for sharing this interesting project.

    I‘m following your guide step by step but cannot connect the pir detector to the esp board.

    Can you please briefly explain how are you connecting the pir detector to the esp32 module (wire color and pin connection).

    Thank you!

  70. Thank you for sharing this interesting project.

    I‘m following your guide step by step but cannot connect the pir detector to the esp board.

    Can you please briefly explain how are you connecting the pir detector to the esp32 module (wire color and pin connection)

  71. Hi Sara, Great website!
    I have uploaded your script using an FTDI chip (no issues). I have the camera working . The flash triggers and the image saved to a 4gb memory card. The web streaming works fine. I have tested the PIR (am312 mini-pir) using a minimal circuit and this works – I can trigger the sensor and light up an LED. I have your circuit setup on a breadboard following your Fritzing diagram but after powerup (USB from laptop – using the FTDI connected to ESP32-CAM, cam to breadboard) the camera flashes but the sensor does not ever trigger for me.
    Parts: ESP32-CAM(ai-thinker), npn 2n2222a, am312 mini-pir
    What am I doing wrong? (I am new to this)

    • After a lot of testing I have got the PIR (am312 mini-pir) detecting motion and triggering the ESP32-CAM led … but it does not take any photo or trigger the flash. I have a 4gb FAT32 formatted card. When I insert it into my sd card reader there are no images saved at all.
      The only code lines I changed are line 143 & 153 – set them to delay(5000);
      Any Ideas why the camera is not taking images?

    • Why is the SD Card not detecting? It is 4gb formatted to FAT32.
      When printing the serial logs I see this:

      rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
      configsip: 0, SPIWP:0xee
      mode:DIO, clock div:1
      entry 0x400805f0
      E (333) esp_core_dump_��ash: No core dump partition found!
      E (333) esp_core_dump_flash: No core dump partition found!
      Starting SD Card
      E (1158) sdmmc_sd: sdmmc_check_scr: send_scr returned 0x109
      E (1158) vfs_fat_sdmmc: sdmmc_card_init failed (0x109).
      SD Card Mount Failed
      No SD Card type found
      Picture file name: /picture136.jpg
      Failed to open file in writing mode
      Going to sleep now

      • Hi.
        That might be an issue with the microSD card, or the connection between the SD card and the ESP32-CAM connector.
        Sometimes, a bad power source might also cause issues with the microSD card slot.

  72. I would suggest looking at the PIR output with an oscilloscope and verify that you have the correct hi or lo level to trigger the wake function. See my comments above.

    Good luck

  73. Hello Sara Santos, can you do an alarm light motion sensor that also does this?
    Like it would light up if it detected a motion, then if that motion stays within the range of the sensor for around 1 minute it would alarm and send a picture on the phone maybe thru a blynk app
    it would be also nice to have a manual turning off on the alarm to turn it off incase of a false alarm
    I hope you would notice this thankssss!!!!!!
    -Jon Breyan

  74. Hi,

    This Esp32 project is great.

    I get this error with the memory card although I have formatted it to Fat32 and 32 kilobits according to the instructions.
    Did you encounter similar problems? Thank you.

    Starting SD Card
    E (2033) sdmmc_common: sdmmc_init_ocr: send_op_cond (1) returned 0x107
    SD Card Mount Failed
    No SD Card attached

    • Hi.
      I think it is an issue with the insert of the SD card. I think it is not connected properly because of the error message “No SD Card attached”.

  75. Hi Sara,

    It’s a great project. I have a problem which I can’t solve. I have connectoed ESP and PIR acc. to scheme. Uploaded code. After input voltage is connected ESP flash once and next PIR doesn’t work. On the SD card I see one photo only. Can you advise what could be wrong in my connection – where looking for reason for that problem.
    Thanks in advance for your help

    • Hi, Sara,

      I have the same problem as Maciej, now in December 2023: the flash will only fire once, and I get only one photo saved to the SD card.

      It will take another photo only if I disconnect and reconnect power, or if I press the reset button on the board.

      I have tried this on two sets of hardware – two ESP32-CAM boards, two cameras, two PIRs, two transistors, two sets of wires and resistors, although I haven’t yet taken the step of checking each individual component.

      On my second board, I tried verifying and uploading the sketch with both Arduino IDEs 1.8.19 and 2.2.1.

      On my first board, I did that with only 2.2.1.

      I know you warn not to use Arduino IDE 2.x yet, but on my first board I have successfully both verified & uploaded the CameraWebServer using 2.x and run the board with that sketch, so I know both the IDE version and the board and camera hardware are OK, even if the second board and camera weren’t.

      I suppose it’s still possible that some of the other components are bad (in my career I have seen two or even more supplier components in a shipment be defective), but note also that I have both 1.8.19 and 2.2.1 up to date and warnings came up in both. When I modified the esp_camera.h from sscb to sccb, those warnings went away but there was no change in behaviour, so while it seems that’s not the solution, or at least not the full solution, I’m including parts of the warnings below in case it’s of any help.

      [ Removed some file location info ]

      ESP32-CAM-PIR-Photo-Capture.ino: In function ‘void setup()’:
      … ESP32-CAM-PIR-Photo-Capture.ino:70:10: warning: ‘camera_config_t::::pin_sscb_sda’ is deprecated: please use pin_sccb_sda instead [-Wdeprecated-declarations]
      config.pin_sscb_sda = SIOD_GPIO_NUM;
      In file included from … ESP32-CAM-PIR-Photo-Capture.ino:16:
      … /.arduino15/packages/esp32/hardware/esp32/2.0.14/tools/sdk/esp32/include/esp32-camera/driver/include/esp_camera.h:123:87: note: declared here
      int pin_sscb_sda attribute((deprecated(“please use pin_sccb_sda instead”))); /*!< GPIO pin for camera SDA line (legacy name) */

      … ESP32-CAM-PIR-Photo-Capture.ino:71:10: warning: ‘camera_config_t::::pin_sscb_scl’ is deprecated: please use pin_sccb_scl instead [-Wdeprecated-declarations]
      config.pin_sscb_scl = SIOC_GPIO_NUM;
      In file included from … ESP32-CAM-PIR-Photo-Capture.ino:16:
      … /.arduino15/packages/esp32/hardware/esp32/2.0.14/tools/sdk/esp32/include/esp32-camera/driver/include/esp_camera.h:127:87: note: declared here
      int pin_sscb_scl attribute((deprecated(“please use pin_sccb_scl instead”))); /*!< GPIO pin for camera SCL line (legacy name) */

      • I found a similar project online with a simpler circuit. On compiling that sketch, the same warnings about pin_sscb_sda and pin_sscb_scl appeared, but I didn’t change code in the sketch. On uploading that sketch, it takes more than one picture (so that issue was not due to a board or camera hardware problem)… but then it keeps taking pictures, every couple of seconds.

        Next I will look at the suggestion by Peter Crayfourd of Dec 31, 2022. The area in which I’m working with my board might be electronically and/or thermally noisy enough to cause false triggers. Other possibilities to look at are power supply and adding a capacitor to the circuit.

        Your recent newsletters have gotten me curious to use a radar sensor, so might give one of those a shot.

        Correction to my previous comment: the changes I made (sscb to sccb) were to ESP32-CAM-PIR-Photo-Capture.ino, not to esp_camera.h.

  76. hi Sara,
    sorry, I use translator, I am french. I am a begginer. Your site is really great. Thank you.
    I have a big problem. I did everything as instructed, several times. I tested 3 cam, 3 MB, 3 micro SD ( 2 and 8 Go), and 3 power supply and 2 PIR. I did not modify the program.
    PIR triggers correctly, flash and in the monitor I read:
    rst:0x5 (DEEPSLEEP_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    configsip: 0, SPIWP:0xee
    mode:DIO, clock div:1
    entry 0x400805f0
    Starting SD Card
    Picture file name: /picture181.jpg
    E (1222) sdmmc_cmd: sdmmc_write_sectors_dma: sdmmc_send_cmd returned 0x109
    E (1222) diskio_sdmmc: sdmmc_write_blocks failed (265)
    Saved file to path: /picture181.jpg
    E (1238) sdmmc_cmd: sdmmc_write_sectors_dma: sdmmc_send_cmd returned 0x109
    E (1238) diskio_sdmmc: sdmmc_write_blocks failed (265)
    Going to sleep now
    When I read the SD card in my computer: empty, nothing. I don’t understand.
    La seule différence avec votre excellent tuto, je n’utilise pas un FTDI mais la MB de la ESP32CAM-MB. Is this the problem?
    Thank you for your attention to my problem.
    Sincerely, Gilbert

  77. I wanted to take a moment to express my sincere appreciation for the outstanding work
    Pls add and external flash synchronization with the built-in LED functionality. i am waiting!

  78. Hi sara, i don’t have the FTDI chip. Can i use the arduino uno to upload the codes to esp32 cam? I notice that the codes does’nt includes any PIR libraries. Hopefully it will work.

  79. I managed to make it work by programming it with an arduino uno. However, it just takes photo every 3 seconds. I have checked my PIR sensor and it is working correctly. What could be the reason?

  80. Hello!
    How should I modify the code so that after the motion was detected and picture was taken, that picture appears in a web server?

  81. Hi Sara,

    Your project is great and inspired me.
    So, I developed an application that can take a photo on PIR and/or timer, save it on SD card and/or send it on a web server.
    All is configurable through a config.txt stored on the SD card, even the sensor paramètres.
    Please take a look at this project and give me your opinion:

  82. Dear Sara, Rui and valued community here,…
    I´ve followed the instructions from the tutorial (which appears well comprehensible to me so far…) but unfortunately don´t get the setup working in respect of motion detection triggered by the PIR sensor.
    After the code has been successfully uploaded, the ESP32 CAM connected to the remaining required component and current applied, the flash LED glims up, flashes once, saves one image to the SD Card, but : nothing else will happen any more later on.
    No reaction to motion detected by the PIR which expected to save additional images in that case to the SD card.
    When I invoke the RST button, the same happens (as perhaps to be expected) as when
    current has been intially applied : LED glims up -> flash -> save image -> bzzzzzz………………
    Initially I felt unsure regarding my fragile wiring on the breadboard, so I soldered everything on to a strip board along with corresponding sockets for the ESP32 CAM and for the PIR sensor mow as well.
    But the behaviour is still the same, as it was, while fiddled to the breadboard with jumper cables, as I´ve tried to describe above.
    I have changed all components to make sure they should be intact. So far unsuccessfully unfortunately.
    Frankly spoken, at last I´m currently not sure weather this relies on the hardware setup, or somehow on the code ?
    Have you / anyone here perhaps experienced that as well ?

    Thanks a lot to you Sara and Rui for all the insight, inspiration and motivation that you do provide and share here !
    Thanks to anyone sharing thought / suggestions, whatever…

    • Hello Karsten, I hope you are doing well and thank you for the detailed explanation.
      Unfortunately based on what you’ve described it’s almost impossible to know what might be wrong..

      It might be a faulty PIR sensor, ESP32-CAM or bad wiring… I can only ensure you that the code from this project is working properly. I can only guess it’s a hardware issue that would require in person debugging.


      • Thanks a lot Rui for your Reply!
        I´ve utilized the PIR sensor test sketch “AM312test.ino” that Thomas Edlinger was so kind to provide @
        It showed that the sensor(s) I´ve have in use here work as required and expected.

        I´ve even tried with a few (brand new| fresh of the pack) ESP32 CAMs.

        It appears as if the signal send from the sensor does not wake up the controller back from deep sleep, for whatever reason…

        I´ve cross checked my wiring and set up plenty of times and it appears to be reliable and robust.

        Thanks again for all your inspiring and interesting work,
        best and continued success and please stay well !

        • Are you using a sensor with 4 volt output and or does you circuit have a dropping resistor because the I/o pins will only tolerate 3 volts. 6 volts will destroy the esp32 cam input.BTDT

    • Hi Karsten,
      I experienced that as well.
      It seems that the PIR sensor is not powered.
      I use a multimeter to measure the 3.3V pin.Found no current.
      Have you solved this problem now?

      • Hi Wes,
        thanks a lot for your reply and for the hint you gave!
        What you wrote/suggested appeared ~ correct, but helped me to “solve” / correct that setting now:
        I was not able to measure a current of 3.3V directly @ the PIR, as you wrote.
        But that current can be measured from the 3.3V Pin of the PIR
        and : the GND Pin directly next to the 5V current input pin!
        Unfortunately I had connected ground to the last Pin labeled as “GND” below GPIO 1.
        This setting still not worked as long as the GND Pin below 5V and the GND
        Pin below GPIO 1 where connected to one another.
        But after I´ve disconnected this two GND Pins fron one another and connected GND of PIR to the GND Pin below 5V Input, the setting worked as expected and required!
        Hey! 🙂
        (Would really like to add an image here…)
        Now it works, but I don´t know why…

        Perhaps Sara and|or Rui could try to explain us the difference between “GND” and “GND” on the ESP32 CAM board ?

        Thanks a lot again and keep well everybody !

        • Congratulate!Karsten,
          Please tolerate it.I am not a native English speaker.
          And I am a beginner.
          You mean that to connect the pir to the 3.3V output pin and the GND Pin directly next to the 5V current input pin,the setting worked?
          But how do you power ESP board?Which GND should be connected to the negative pole of the power supply?
          In fact, the problem I have is that it can’t stop taking pictures.
          Let me reconfirm that your work can successfully detect motion and take pictures now?

          • Hi Wes,
            no need for excuses, what you wrote appears very comprehensible to me!
            Yes, I confirm that motion triggered photos are now generated, by applying the setting as described.
            I´ve never observed that the ESP32 CAM has not stopped taken photos.
            In my previous setup I took on photo after power on, before it went to sleep forever.
            I have soldered everything to a breadboard an the GND pin near +5V input is shared by the ESP board and the PIR.
            Really a shame that we can´t share photos / illustrations here…

            The GND pin I´ve selected before is labeled as “GND/R” on my module here, whatever that may mean to us.

            Rui | Sara @ randomnerdtutorials :
            Are you able to explain, why “GND” is not eq. “GND” here ?

          • Hi Gaurav,

            I´ve send some photos of the circuit I´ve assembled here already yesterday via Mail.
            Just let ne know in the case there is anything else I could do.
            Good success and have fun


  83. Hi,
    I am following your tutorial but the camera is not taking pictures.
    I have tried everything. I have no idea whats happening

    rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    configsip: 0, SPIWP:0xee
    mode:DIO, clock div:1
    entry 0x400805e4
    Starting SD Card
    Camera capture failed

      • Hello, thank you for your reply.
        I have tried that. The problem is not that it times out, everything goes well, no errors. Its just that the photo is not taken, even though the flash is working. If I reset again the flash goes of again and I get the same message in the serial “camera capture failed”. I have tried to check if the problem is with the buffer variable (fb) that apparently triggers the condition fi (!fb)

        I don’t know what to try anymore. It has occurred to me that maybe the ov2640 is faulty, even though it is recognized by the board and it does not fail. It just does not take pictures. I have tried unplug and plug again multiple times to no avail.

        On the other hand, when I made the circuit with the IF sensor, the flash flashes when I give power to the circuit. It also flashes when I reset the esp board. Other than that it does not do anything. I tried multiple sensors and it does not work. Probably because of the first error of not taking a photo on reset/power on. The SD card is always empty.

        Thank you in advance for your help

          • Hi,

            Yes just tried another one. Same issue. Pretty sure the camera is faulty. I will report back once I try another camera.
            Thank you for your time

  84. Not triggering sensor …

    I would suggest looking at the PIR output with an oscilloscope and verify that you have the correct hi or lo level to trigger the wake function.

  85. I had conneted the same circit but it wont works and i checked esp32 cam and pir sensor individually then they works properly but when i connect the actual circuit the cam wont takes any photos and i used same components please help me

  86. I have implemented the same according to the tutorial. But the problem is that whenever i am plugging in the battery it is capturing the image and after that it is not working. What could be the reason and what is the solution?
    One more requirement if you can fulfill- can we save the captured images in our laptop folder rather than sd card?

  87. Hi, is it possible to make it wakes up faster, my application requires it to take a photo of an object that’s falling.

  88. I’m having a strange issue where serial monitor will print “sd card mount failed” and the camera will crash if the pin is held low too long or if the PIR sensor in the circuit trips repeatedly. thought GPIO13 was data3 for SD card so tried changing to GPIO12 and had the same issue.


Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.