What You Will Build
This project turns an ESP32-CAM into an environment monitor with a memory. A DHT22 sensor measures temperature and humidity, the board calculates the dew point, and all three values appear live on a Blynk dashboard. At the same time the camera takes a time-lapse photo at an interval you set from the app and saves it to a microSD card, while a CSV file logs the readings so you can graph them later.
It is a good fit for a greenhouse, a grow tent, a 3D printer enclosure, a workshop, or a plant on a windowsill, anywhere you want both a number and a picture of what was happening when that number changed.
The interesting engineering is in the details that most tutorials skip: which ESP32-CAM pins you can really use, why analog sensors are off the table, how to share the microSD slot with a sensor, how to tell the difference between "the sensor reads 0" and "the sensor is broken", and why the sensor must not sit right next to the board.
Where the Data Goes
Each kind of data goes where it is most useful:
| Data | Destination | Why |
|---|---|---|
| Temperature, humidity, dew point | Blynk dashboard, every 10 seconds | Live view and history charts from anywhere |
| Sensor and card status | Blynk status label | You see a fault immediately |
| Time-lapse photos | microSD card, /photos/ | Images are too large to stream to a free dashboard, and the card keeps them safely |
| Readings with timestamps | microSD card, /log.csv, every minute | A permanent record you can open in a spreadsheet |
| Photo interval and "photo now" | Blynk controls | Change behaviour without reflashing |
Keeping photos on the card, rather than pushing them to the cloud, makes the project cheap to run and keeps your images private. The trade-off is that you need to visit the card to collect them, or add an upload path later.
Components
7 itemsNeed these parts? Get this build sheet by email
Parts list with buy links, plus new builds as they're published. By subscribing you agree to our Privacy Policy. Unsubscribe anytime.
Plan Your Pins Before You Wire Anything
The AI-Thinker ESP32-CAM leaves very few pins free. Camera data and control use GPIO 5, 18, 19, 21, 22, 23, 25, 26, 27, 32, 34, 35, 36, 39 and 0. GPIO 16 belongs to the PSRAM. GPIO 1 and 3 are the serial port. That leaves the six header pins GPIO 12, 13, 14, 15, 2 and 4, and those are also the microSD interface.
Three consequences shape this design:
1. No analog sensors. All six header pins are on ADC2, and the ESP32 cannot read ADC2 while Wi-Fi is active. A thermistor or soil-moisture probe on these pins will give garbage or errors. Use digital sensors, such as a DHT22, a DS18B20 or a digital I2C sensor.
2. Use the microSD in 1-bit mode. By default the SD card uses four data lines on GPIO 2, 4, 12 and 13, plus clock and command on 14 and 15. In 1-bit mode it needs only GPIO 2 (data), 14 (clock) and 15 (command). That frees GPIO 4, 12 and 13, and it stops the flash LED, which shares GPIO 4, from flashing every time the card is accessed.
3. Pick the pin carefully. GPIO 12 is a strapping pin. If it is pulled HIGH at boot, a 3.3 V flash module will not start, so avoid putting a sensor with a pull-up on it. GPIO 4 drives the flash LED. That makes GPIO 13 the cleanest choice for a single-wire sensor. GPIO 13 doubles as the SD card's DAT3 line, which the card ignores in 1-bit mode after start-up. The sketch mounts the card before the first sensor read for this reason. If your card fails to mount with the sensor connected, test it with the sensor unplugged to confirm this is the cause.
For a complete pin reference, see the ESP32-CAM Pinout Guide.
Wiring
| DHT22 module | ESP32-CAM |
|---|---|
| VCC (+) | 3V3 |
| DATA (OUT) | GPIO 13 |
| GND (−) | GND |
The DHT22 runs from 3.3 V to 5.5 V. Powering it from 3V3 keeps its data line at 3.3 V logic, which matches the ESP32. A bare DHT22 needs a 4.7 kΩ to 10 kΩ pull-up resistor between DATA and VCC, and most modules already include one.
Keep the Sensor Away From the Board
An ESP32-CAM running Wi-Fi and the camera becomes noticeably warm, often several degrees above room temperature. A sensor taped next to it reads high, and the error also pushes the humidity low. Mount the DHT22 on a short lead, at least 10 to 15 cm away, out of the warm air rising from the board and out of direct sunlight. Compare it against a second thermometer for an hour before trusting it.
Programming Connections
Connect an FTDI adapter set to 3.3 V logic: GND to GND, 5V to 5V, TX to U0R and RX to U0T. Connect GPIO 0 to GND to enter flash mode, press reset, upload, then remove the jumper and press reset again.
⚠️ Warning
Fix power first. Camera start-up and Wi-Fi transmission cause sharp current spikes. A weak supply or thin cable leads to brownout resets or "camera init failed". Use a 5 V 2 A supply, a short thick cable and a 470 to 1000 µF capacitor across 5V and GND. A microSD card also draws a burst of current when it is written to.
About the DHT22
The DHT22 is a digital sensor with a built-in analog-to-digital converter that sends a 40-bit reading over a single data wire. Typical datasheet figures are a range of −40 to 80 °C with about ±0.5 °C accuracy, and 0 to 100 % relative humidity with roughly ±2 to 5 % accuracy. It can be read at most once every 2 seconds, so reading more often returns errors.
Treat those accuracy figures as the best case. In practice sensors drift, and humidity readings in condensing conditions can be unreliable.
Dew Point: A Useful Derived Value
The firmware also calculates the dew point, the temperature at which water vapour would start to condense. It uses the Magnus formula with constants a = 17.62 and b = 243.12 °C:
gamma = ln(RH / 100) + (a × T) / (b + T)
dew point = (b × gamma) / (a − gamma)It matters because mould and condensation form on surfaces at or below the dew point. If your greenhouse glass or enclosure wall is close to that temperature, you will see condensation, even though the air itself looks dry.
Fault, Not Zero
A disconnected DHT22 returns "not a number" rather than zero. The firmware counts consecutive failed reads and, after three, marks the sensor as faulty and stops publishing values so the dashboard never shows a plausible-looking but invented number. The status label turns to SENSOR FAULT instead.
Set Up Blynk
Create a template in Blynk.Console with hardware ESP32 and connection WiFi, then add these datastreams:
| Pin | Name | Type | Notes |
|---|---|---|---|
| V0 | Temperature | Double, °C | Chart and gauge |
| V1 | Humidity | Double, % | Chart and gauge |
| V2 | Dew point | Double, °C | Optional |
| V3 | Status | String | OK, SENSOR FAULT or NO SD CARD |
| V4 | Wi-Fi signal | Integer, dBm | Optional |
| V5 | Photo interval | Integer, 0 to 240 minutes, default 10 | Slider. 0 turns the time-lapse off |
| V6 | Photo now | Integer 0 to 1 | Button |
| V7 | Photos saved | Integer | Optional |
Datastream and widget limits depend on your Blynk plan and can change. If you hit a limit, drop the optional ones first. Build a dashboard with a chart for V0 and V1, a label for V3, a slider for V5 and a button for V6, then create a device and copy its Template ID, Template Name and Auth Token.
In the Arduino IDE, install the esp32 by Espressif Systems board package, plus the Blynk (1.3.x), DHT sensor library (Adafruit) and Adafruit Unified Sensor libraries. Select AI Thinker ESP32-CAM and set the partition scheme to Huge APP (3MB No OTA/1MB SPIFFS).
// ESP32-CAM sensor monitor with Blynk and microSD time-lapse
// Board: AI Thinker ESP32-CAM | Partition: Huge APP | Blynk library 1.3.x
#define BLYNK_TEMPLATE_ID "TMPLxxxxxxxx"
#define BLYNK_TEMPLATE_NAME "ESP32-CAM Monitor"
#define BLYNK_AUTH_TOKEN "YOUR_BLYNK_AUTH_TOKEN"
#define BLYNK_PRINT Serial
#include <WiFi.h>
#include <BlynkSimpleEsp32.h>
#include <DHT.h>
#include "esp_camera.h"
#include "FS.h"
#include "SD_MMC.h"
#include <time.h>
const char* WIFI_SSID = "YOUR_SSID";
const char* WIFI_PASS = "YOUR_PASSWORD";
const char* TZ_INFO = "IST-5:30"; // change for your time zone
#define DHT_PIN 13
#define DHT_TYPE DHT22
#define FLASH_PIN 4
const framesize_t PHOTO_SIZE = FRAMESIZE_SXGA; // 1280x1024
// ---------- 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
DHT dht(DHT_PIN, DHT_TYPE);
BlynkTimer timer;
float tempC = NAN, hum = NAN, dewC = NAN;
uint8_t failCount = 0;
bool sensorOk = false;
bool sdOk = false;
uint32_t photoIntervalMin = 10;
uint32_t lastPhotoAt = 0;
uint32_t photoCount = 0;
volatile bool captureRequested = false;
// ---------- 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 = PHOTO_SIZE;
c.jpeg_quality = 10;
c.fb_count = 2;
c.fb_location = CAMERA_FB_IN_PSRAM;
c.grab_mode = CAMERA_GRAB_LATEST;
return esp_camera_init(&c) == ESP_OK;
}
camera_fb_t* captureFresh() {
camera_fb_t* fb = nullptr;
for (int i = 0; i < 3; i++) { // let auto-exposure settle
fb = esp_camera_fb_get();
if (fb) esp_camera_fb_return(fb);
delay(80);
}
return esp_camera_fb_get();
}
// ---------- microSD ----------
bool initSD() {
if (!SD_MMC.begin("/sdcard", true)) return false; // 1-bit mode
pinMode(FLASH_PIN, OUTPUT);
digitalWrite(FLASH_PIN, LOW); // keep the flash LED off
if (SD_MMC.cardType() == CARD_NONE) return false;
SD_MMC.mkdir("/photos");
return true;
}
String isoTime() {
struct tm t;
if (!getLocalTime(&t, 100)) return "time-not-set";
char buf[24];
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &t);
return String(buf);
}
bool savePhoto() {
if (!sdOk) return false;
camera_fb_t* fb = captureFresh();
if (!fb) { Serial.println("Capture failed"); return false; }
char name[48];
struct tm t;
if (getLocalTime(&t, 100)) strftime(name, sizeof(name), "/photos/%Y%m%d_%H%M%S.jpg", &t);
else snprintf(name, sizeof(name), "/photos/boot_%lu.jpg", (unsigned long)millis());
const size_t len = fb->len;
size_t written = 0;
File f = SD_MMC.open(name, FILE_WRITE);
if (f) { written = f.write(fb->buf, len); f.close(); }
esp_camera_fb_return(fb);
if (written != len) { Serial.println("SD write failed"); return false; }
photoCount++;
Serial.printf("Saved %s (%u bytes)\n", name, (unsigned)len);
return true;
}
void logCsv() {
if (!sdOk || !sensorOk) return;
const bool isNew = !SD_MMC.exists("/log.csv");
File f = SD_MMC.open("/log.csv", FILE_APPEND);
if (!f) return;
if (isNew) f.println("time,temp_c,humidity_pct,dew_point_c");
f.printf("%s,%.1f,%.1f,%.1f\n", isoTime().c_str(), tempC, hum, dewC);
f.close();
}
// ---------- Sensor ----------
void readSensor() {
const float h = dht.readHumidity();
const float t = dht.readTemperature();
if (isnan(h) || isnan(t)) {
if (failCount < 255) failCount++;
if (failCount >= 3) sensorOk = false;
return;
}
failCount = 0;
sensorOk = true;
tempC = t;
hum = h;
if (h > 0) { // dew point (Magnus formula)
const float g = log(h / 100.0) + (17.62 * t) / (243.12 + t);
dewC = 243.12 * g / (17.62 - g);
}
}
const char* statusText() {
if (!sensorOk) return "SENSOR FAULT";
if (!sdOk) return "NO SD CARD";
return "OK";
}
void publishData() {
if (!Blynk.connected()) return;
if (sensorOk) { // never publish stale or invented values
Blynk.virtualWrite(V0, tempC);
Blynk.virtualWrite(V1, hum);
Blynk.virtualWrite(V2, dewC);
}
Blynk.virtualWrite(V3, statusText());
Blynk.virtualWrite(V4, WiFi.RSSI());
Blynk.virtualWrite(V7, photoCount);
}
// ---------- Blynk handlers ----------
BLYNK_CONNECTED() {
Blynk.syncVirtual(V5);
}
BLYNK_WRITE(V5) {
photoIntervalMin = constrain(param.asInt(), 0, 240);
}
BLYNK_WRITE(V6) {
if (param.asInt() == 1) captureRequested = true;
}
void maintainConnections() {
static uint32_t lastTry = 0;
if (millis() - lastTry < 10000) return;
if (WiFi.status() != WL_CONNECTED) {
lastTry = millis();
WiFi.reconnect();
} else if (!Blynk.connected()) {
lastTry = millis();
Blynk.connect(3000);
}
}
void setup() {
Serial.begin(115200);
if (!initCamera()) {
Serial.println("Camera init failed - check power and the board selection");
delay(5000);
ESP.restart();
}
sdOk = initSD(); // mount the card before the first sensor read
Serial.println(sdOk ? "microSD ready" : "microSD not available");
dht.begin();
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
const uint32_t t0 = millis();
while (WiFi.status() != WL_CONNECTED && millis() - t0 < 20000) delay(250);
configTzTime(TZ_INFO, "pool.ntp.org", "time.google.com");
Blynk.config(BLYNK_AUTH_TOKEN);
timer.setInterval(5000L, readSensor); // DHT22 needs 2 s minimum
timer.setInterval(10000L, publishData);
timer.setInterval(60000L, logCsv);
}
void loop() {
maintainConnections();
if (Blynk.connected()) Blynk.run();
timer.run();
const uint32_t now = millis();
const bool due = photoIntervalMin > 0 && (now - lastPhotoAt >= photoIntervalMin * 60000UL);
if (captureRequested || due) {
captureRequested = false;
lastPhotoAt = now;
savePhoto();
}
}How the Firmware Works
Several jobs, one loop. BlynkTimer runs the sensor read every 5 seconds, the dashboard update every 10 seconds and the CSV log every minute, while loop() checks whether a photo is due. No delay() calls hold things up, apart from the short settling waits when taking a photo.
Photos in loop(), not in callbacks. The "photo now" button and the slider only set variables. The slow camera and SD work happens in loop(), so the Blynk connection stays serviced.
Fresh frames. After sitting idle, the camera's buffers hold old frames, and auto-exposure needs a few frames to settle. captureFresh() throws away three frames before keeping one, which noticeably improves brightness and colour.
Failure is visible. If the sensor fails three reads in a row, values stop updating and the status says SENSOR FAULT. If the card is missing, the status says NO SD CARD. Because Blynk already shows when the whole device is offline, you can tell all three cases apart.
Time-stamped files. NTP time gives each photo and log line a real timestamp, such as /photos/20261019_143210.jpg. If the time has not synchronised yet, the photo falls back to a boot_<milliseconds> name rather than being lost.
Working With the Card
Format the card FAT32, and use 32 GB or less, because larger cards are usually formatted exFAT, which the ESP32 library does not read. A photo at 1280×1024 and JPEG quality 10 typically comes to roughly 100 to 250 KB, depending on the scene. At one photo every 10 minutes that is 144 photos a day, or a few tens of megabytes, so even a small card lasts for months. Check the first few photos and adjust PHOTO_SIZE or quality to suit.
To turn the photos into a time-lapse video on your computer, put the files in a folder and run ffmpeg:
ffmpeg -framerate 24 -pattern_type glob -i "*.jpg" -c:v libx264 -pix_fmt yuv420p timelapse.mp4Open log.csv in any spreadsheet and chart the columns. Because every row has a timestamp, you can line up a change in the photos with a change in the readings, for example a dip in humidity right when the vents opened.
Test and Calibrate
- Camera and card first. Upload with the sensor disconnected and confirm the Serial Monitor reports "microSD ready" with no camera error.
- Sensor alone. Connect the DHT22 and watch for readings. Unplug its data wire and confirm the status changes to SENSOR FAULT after about 15 seconds.
- Blynk. Confirm the charts update and the device shows online.
- Photo on demand. Press Photo now and check that a time-stamped file appears on the card.
- Interval. Set the slider to 1 minute for a short test, then back to your real interval.
- Compare against a reference. Put a trusted thermometer next to the DHT22 for an hour. A small constant offset is normal, and you can correct it in firmware. A large or drifting error means self-heating from the board.
- Outage. Turn off the router and confirm photos and the CSV log keep working, then restart it and confirm Blynk reconnects.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
| "Camera init failed" | Weak power, wrong board or PSRAM off | Use a 2 A supply and a capacitor, and select AI Thinker ESP32-CAM |
| "microSD not available" | Wrong format, card over 32 GB or card not seated | Format FAT32 and reseat the card |
| Card mounts only without the sensor | The sensor shares the card's DAT3 line on GPIO 13 | Mount first (as the sketch does), try another sensor module, or use a different single-wire sensor pin plan |
| Board will not boot | Something pulls GPIO 12 HIGH, or GPIO 0 is still grounded | Keep GPIO 12 free and remove the programming jumper |
| Flash LED lights during SD writes | Card running in 4-bit mode | Keep SD_MMC.begin("/sdcard", true) |
| Readings read high | Sensor too close to the warm board | Move it 10 to 15 cm away on a lead |
| Status shows SENSOR FAULT | Loose data wire, no pull-up or reads too frequent | Check wiring and keep reads at 2 seconds or slower |
| Photos too dark or too bright | Exposure not settled | Keep the discarded frames, and add light |
| Photo not saved, "SD write failed" | Card full, corrupted or removed | Check the card and free space |
| Times are wrong | Time zone string not set | Change TZ_INFO for your location |
| Sketch too big | Wrong partition scheme | Choose Huge APP (3MB No OTA) |
Where to Go Next
Good extensions include a flash LED for night shots (with the card in 1-bit mode GPIO 4 is free to drive it), a second single-wire sensor such as a DS18B20 for a soil or water temperature, and a Blynk event that warns you when the dew point comes within a couple of degrees of the temperature.
Keep your Wi-Fi password and Blynk token out of screenshots and public repositories, and remember that photos of a home or workplace are personal data.
Related reading: ESP32-CAM Photo Capture with MicroSD Storage, ESP32-CAM Time-Lapse Recorder, the Blynk 2.0 complete guide, and the companion ESP32-CAM Blynk Security System and Motion Snapshot Dashboard.
Official references: the Blynk documentation and the datasheets for the ESP32 and DHT22.


