Skip to content

ESP32 · Build guide

ESP32-CAM Photo Capture to microSD Card: Complete Sketch, File Naming and Web Download

Capture JPEG photos with the ESP32-CAM and save them directly to a microSD card, with sequential file naming so nothing gets overwritten.

ESP32-CAM Photo Capture to microSD Card: Complete Sketch, File Naming and Web Download
Difficulty
Beginner
Read time
5 min
Board
ESP32
Author
Shantanu Kumar Mohanty
Published
Oct 26, 2026
Views
8

Every ESP32-CAM project that keeps pictures, whether a motion trigger, a doorbell or a timelapse, needs the same foundation: write each JPEG to the microSD card under a unique name, make sure it really was saved, and get the photos back off the board. This project builds that foundation with the AI-Thinker board's built-in card slot.

Quick answer: format a 32 GB or smaller card as FAT32, mount it with SD_MMC.begin("/sdcard", true) (the true selects 1-bit mode, which keeps the flash LED from flickering and frees GPIO 4, 12 and 13), capture a frame with esp_camera_fb_get(), write fb->buf to a file, and check that the number of bytes written equals fb->len. Keep the file counter in flash with Preferences, not in RAM, so names stay unique after a power cut. The complete sketch below takes a photo each time you press a button, then sleeps.

What You Need

Components

5 items
NameQtyLink
ESP32-CAM (AI-Thinker) with OV2640 camera×1—
ESP32-CAM-MB programmer base, or a USB-serial adapter for flashing×1—
microSD card, 32 GB or smaller, formatted FAT32×1—
Push button (any momentary switch)×1—
5 V power supply, 1 A or more×1—

Need 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.

How the Card Slot Is Wired

The AI-Thinker board connects its microSD slot to the ESP32's SD/MMC peripheral, so you use the SD_MMC library, not the SPI SD library used with separate card modules. SD/MMC can run in 4-bit or 1-bit mode:

Card lineGPIO4-bit mode (SD_MMC.begin())1-bit mode (SD_MMC.begin("/sdcard", true))
CLK14UsedUsed
CMD15UsedUsed
D02UsedUsed
D14Used (also the flash LED)Free
D212UsedFree
D313UsedFree

Use 1-bit mode. It's a little slower, which doesn't matter for photos, but it stops the bright flash LED on GPIO 4 flickering with every card access and leaves GPIO 13 free for a button or PIR sensor. The full pin picture is in the ESP32-CAM pinout guide.

⚠️ Warning

Format the card as FAT32, not exFAT, and use a card of 32 GB or smaller for the first build. Cards above 32 GB come formatted as exFAT and won't mount until reformatted; Windows can't format them as FAT32 from Explorer, so use the free SD Card Formatter or a FAT32 formatting tool. Insert and remove the card only with the power off.

Complete Sketch: A Photo on Every Button Press

Wire a push button between GPIO 13 and GND. Each press wakes the board from deep sleep; it takes one photo, saves it with the next number (/img_00001.jpg, /img_00002.jpg, ...), and goes back to sleep, drawing very little power in between. The sketch works on Arduino-ESP32 core 2.0.x and 3.x. Select AI Thinker ESP32-CAM as the board, and keep PSRAM enabled.

sketch.ino
// ESP32-CAM: save a photo to microSD on every button press, then deep sleep
// SolderHub.com | AI-Thinker ESP32-CAM | Button: GPIO 13 to GND
#include "esp_camera.h"
#include "FS.h"
#include "SD_MMC.h"
#include <Preferences.h>
#include "driver/rtc_io.h"

// 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

#define FLASH_LED   GPIO_NUM_4
#define WAKE_BUTTON GPIO_NUM_13

Preferences prefs;

bool initCamera() {
  camera_config_t c = {};
  c.ledc_channel = LEDC_CHANNEL_0;
  c.ledc_timer   = LEDC_TIMER_0;
  c.pin_d0 = Y2_GPIO_NUM;  c.pin_d1 = Y3_GPIO_NUM;  c.pin_d2 = Y4_GPIO_NUM;  c.pin_d3 = Y5_GPIO_NUM;
  c.pin_d4 = Y6_GPIO_NUM;  c.pin_d5 = Y7_GPIO_NUM;  c.pin_d6 = Y8_GPIO_NUM;  c.pin_d7 = Y9_GPIO_NUM;
  c.pin_xclk  = XCLK_GPIO_NUM;  c.pin_pclk = PCLK_GPIO_NUM;
  c.pin_vsync = VSYNC_GPIO_NUM; c.pin_href = HREF_GPIO_NUM;
  c.pin_sccb_sda = SIOD_GPIO_NUM; c.pin_sccb_scl = SIOC_GPIO_NUM;
  c.pin_pwdn  = PWDN_GPIO_NUM;  c.pin_reset = RESET_GPIO_NUM;
  c.xclk_freq_hz = 20000000;
  c.pixel_format = PIXFORMAT_JPEG;
  c.frame_size   = FRAMESIZE_SVGA;     // 800x600: start here, raise once it works
  c.jpeg_quality = 12;                 // 10-15 is a good range; lower = better quality, bigger file
  c.fb_count     = 1;
  c.fb_location  = CAMERA_FB_IN_PSRAM;
  c.grab_mode    = CAMERA_GRAB_LATEST;
  return esp_camera_init(&c) == ESP_OK;
}

void goToSleep() {
  // Keep the flash LED off while asleep, and wake when the button pulls GPIO 13 low
  pinMode(FLASH_LED, OUTPUT);
  digitalWrite(FLASH_LED, LOW);
  rtc_gpio_hold_en(FLASH_LED);
  rtc_gpio_pullup_en(WAKE_BUTTON);
  rtc_gpio_pulldown_dis(WAKE_BUTTON);
  esp_sleep_enable_ext0_wakeup(WAKE_BUTTON, 0);
  Serial.println("Sleeping until the next button press");
  Serial.flush();
  esp_deep_sleep_start();
}

void setup() {
  Serial.begin(115200);
  rtc_gpio_hold_dis(FLASH_LED);        // release the hold from the previous sleep

  if (!initCamera()) { Serial.println("Camera init failed"); goToSleep(); }

  // Let auto-exposure settle: the first frames after power-up are often dark
  for (int i = 0; i < 3; i++) {
    camera_fb_t *f = esp_camera_fb_get();
    if (f) esp_camera_fb_return(f);
  }

  if (!SD_MMC.begin("/sdcard", true)) {   // true = 1-bit mode
    Serial.println("SD card mount failed: check FAT32 format and seating");
    goToSleep();
  }
  if (SD_MMC.cardType() == CARD_NONE) { Serial.println("No SD card"); goToSleep(); }

  prefs.begin("camera", false);
  uint32_t next = prefs.getUInt("photo", 0) + 1;
  char path[24];
  snprintf(path, sizeof(path), "/img_%05lu.jpg", (unsigned long)next);

  camera_fb_t *fb = esp_camera_fb_get();
  if (!fb) {
    Serial.println("Capture failed");
  } else {
    File file = SD_MMC.open(path, FILE_WRITE);
    size_t written = file ? file.write(fb->buf, fb->len) : 0;
    if (file) file.close();

    if (written == fb->len) {
      prefs.putUInt("photo", next);     // only count photos that really saved
      Serial.printf("Saved %s (%u bytes)\n", path, (unsigned)fb->len);
    } else {
      Serial.printf("Write failed for %s: %u of %u bytes\n", path, (unsigned)written, (unsigned)fb->len);
    }
    esp_camera_fb_return(fb);            // always return the buffer, even after an error
  }
  prefs.end();
  goToSleep();
}

void loop() {}   // never reached: each wake runs setup() and sleeps again
ESP32-CAM workflow: trigger, capture, save, verify

How the sketch keeps photos safe

  • The counter lives in flash. Preferences stores it in the ESP32's NVS flash, so numbering continues after a power cut. A counter in RTC_DATA_ATTR memory survives deep sleep but resets when power is lost, and then new photos overwrite old ones.
  • The counter only advances after a successful save. A failed write doesn't leave a gap or a fake file.
  • written == fb->len proves the whole JPEG reached the card. A full card or a loose card can open a file and then write nothing.
  • The frame buffer is always returned, even on errors. Forgetting it leaks the buffer and the next capture fails.
  • Zero-padded names (img_00042.jpg) sort correctly in every file browser.

Adapting the Sketch

Use a PIR sensor instead of a button. Most PIR modules (such as the HC-SR501) drive their output HIGH on motion, so wire the output to GPIO 13 and wake on a HIGH level: replace the pull-up lines with rtc_gpio_pulldown_en(WAKE_BUTTON); rtc_gpio_pullup_dis(WAKE_BUTTON); and use esp_sleep_enable_ext0_wakeup(WAKE_BUTTON, 1). Set the PIR's own delay short, so it has gone LOW again before the board finishes saving, or it wakes straight back up. The complete motion build is in the PIR motion detection camera.

Take a photo every few minutes. Replace the ext0 wake with a timer, for example esp_sleep_enable_timer_wakeup(10ULL * 60 * 1000000) for every 10 minutes. That turns the sketch into a battery timelapse camera.

Raise the resolution. Once SVGA works reliably, try FRAMESIZE_XGA (1024x768) or FRAMESIZE_UXGA (1600x1200). Larger frames take longer to capture and write and need PSRAM, and they expose a weak power supply faster. If the board starts resetting, step back one size.

Improve image quality. Lower jpeg_quality (for example 10) gives sharper pictures and larger files. After initCamera(), sensor_t *s = esp_camera_sensor_get(); gives access to settings such as s->set_vflip(s, 1) to flip the image or s->set_whitebal(s, 1) for automatic white balance.

Save power. Each wake costs roughly a second or two of camera and card activity at a few hundred milliamps, and the board then sleeps at far lower current. On battery, run the board without the ESP32-CAM-MB base (its USB chip draws current all the time), and remember that the AI-Thinker board's own regulator and power LED draw far more than the ESP32 does in deep sleep. The ESP32 deep sleep guide covers the numbers.

Browsing and Downloading Photos Over WiFi

Pulling the card and reading it on a computer works, but it means physically accessing the board every time. A small web server running on the ESP32-CAM itself can list and serve saved files over the local network instead. This version stays awake rather than sleeping, so use it as a separate sketch (or a mode you switch to with a jumper). Connect to Wi-Fi as in the ESP32-CAM web server guide, mount the card in 1-bit mode, then call setupServer() and run server.handleClient() in loop().

sketch.ino
#include <WebServer.h>
WebServer server(80);

void handleFileList() {
  File root = SD_MMC.open("/");
  String html = "<!doctype html><meta name=viewport content='width=device-width'><h2>Saved photos</h2><ul>";
  for (File f = root.openNextFile(); f; f = root.openNextFile()) {
    String name = f.name();                       // e.g. "img_00001.jpg"
    if (name.endsWith(".jpg")) {
      html += "<li><a href='/" + name + "'>" + name + "</a> (" + String(f.size() / 1024) + " KB)</li>";
    }
  }
  html += "</ul><p>Free: " + String((SD_MMC.totalBytes() - SD_MMC.usedBytes()) / (1024 * 1024)) + " MB</p>";
  server.send(200, "text/html", html);
}

void handleFileDownload() {
  String path = server.uri();                     // e.g. "/img_00001.jpg"
  if (path.indexOf("..") >= 0 || !path.endsWith(".jpg")) {   // only serve photos, nothing else
    server.send(404, "text/plain", "Not found");
    return;
  }
  File file = SD_MMC.open(path, FILE_READ);
  if (!file) { server.send(404, "text/plain", "Not found"); return; }
  server.streamFile(file, "image/jpeg");
  file.close();
}

void setupServer() {
  server.on("/", handleFileList);
  server.onNotFound(handleFileDownload);
  server.begin();
}

Open the board's IP address in a browser on the same Wi-Fi to see the list and tap a photo to download it. Keep this server on your home network: don't port-forward it to the internet. This same list-and-serve pattern is what the fingerprint security system's access log and the smart doorbell's photo alerts build on.

Managing Card Capacity

JPEG size depends on resolution, quality and the scene. As a rough guide, SVGA (800x600) at quality 12 is often 40–80 KB and UXGA (1600x1200) 150–300 KB, so a 32 GB card holds hundreds of thousands of SVGA photos. A busy timelapse can still fill it, and a full card makes writes fail quietly. Check free space before each save and act on it:

sketch.ino
uint64_t freeBytes = SD_MMC.totalBytes() - SD_MMC.usedBytes();
if (freeBytes < 5ULL * 1024 * 1024) {      // keep at least 5 MB free
  Serial.println("Card nearly full");
  // delete the oldest file, or stop capturing and report it
}

With numbered files, the oldest photo is the one with the lowest number, so a rolling store can delete img_ + (current number minus the number of photos to keep).

ESP32-CAM storage decision loop

Common Mistakes

MistakeWhat happensFix
Using the SPI SD libraryCard not found with the default pinsUse SD_MMC, which matches the board's wiring
SD_MMC.begin() with no argumentsFlash LED flickers; GPIO 4, 12, 13 takenSD_MMC.begin("/sdcard", true)
exFAT cardMount failsReformat as FAT32
Counter in RTC_DATA_ATTR onlyPhotos overwritten after a power cutStore it with Preferences
Not checking bytes writtenEmpty or missing photos you only discover laterCompare written with fb->len
Sensor on GPIO 12 at bootBoard won't boot (wrong flash voltage)Use GPIO 13 for inputs

Troubleshooting

SymptomLikely causeFix
SD card mount failedNot FAT32, card not seated, card too largeReformat as FAT32; reseat; try a 16–32 GB card
Camera init failedRibbon cable loose, wrong pin map, PSRAM offReseat the ribbon (contacts facing the board); AI-Thinker pins; PSRAM enabled
First photo is dark or green-tintedAuto-exposure not settledKeep the discarded warm-up frames; add a short delay
Photos are 0 bytesCapture failed but was written anywayCheck fb before writing, as in the sketch
Board resets while savingSupply too weak for camera plus card5 V 1 A supply, short leads, 470 µF capacitor on 5 V
Never wakes from sleepButton on the wrong pin, or no pull-upGPIO 13 to GND; keep rtc_gpio_pullup_en()
Flash LED glows dimly while asleepGPIO 4 not held lowKeep the rtc_gpio_hold_en() line
Download page shows 404Link path and opened path differLinks must start with / and match the file name exactly

FAQ

Can I use a card larger than 32 GB? Often yes, once it's reformatted as FAT32, but 32 GB and smaller cards are the most reliable choice.

How many photos fit on the card? At SVGA and quality 12, hundreds of thousands on a 32 GB card. Measure a few of your own files to estimate.

Why use the SD card instead of Wi-Fi? It keeps photos when Wi-Fi is down and uses far less power per photo. Wi-Fi-only builds such as the Telegram camera bot skip the card.

Can I add the date to file names? Only once the board knows the time: sync it with NTP over Wi-Fi first, or add an RTC module. Without that, numbered names are more reliable.

Does the flash LED fire for photos? Not in this sketch. To use it, set GPIO 4 HIGH just before esp_camera_fb_get() and LOW after; keep the flashes short, as the LED gets hot.

Is there anything to consider about privacy? Yes. Point the camera only where you have permission, and protect the card: anyone who removes it can read every photo.

Where to Go Next

This storage pattern is the foundation for several other projects:

Topicsesp32-cam sd cardesp32-cam save photosd_mmcesp32-cam microsdesp32-cam deep sleepai-thinkeresp32-camphoto capture

Questions & Answers