In this guide
SD Card Data Logging for ESP32 and Arduino Projects
Quick answer: An SD card module lets your ESP32 or Arduino record sensor readings as a CSV file without a computer attached: wire the module over SPI, format the card as FAT32, open the file in append mode, and write one comma-separated line per reading with a timestamp. Use short 8.3 filenames on an Arduino Uno, flush the file regularly, and add an RTC module for real timestamps — then read the CSV in Python or Excel.
| Step | What to do |
|---|---|
| 1 | Pick the module: 3.3 V logic for ESP32, level-shifted 5 V module for Uno |
| 2 | Format the card as FAT32 (cards up to 32 GB) |
| 3 | Wire SPI: MOSI, MISO, SCK plus one CS pin |
| 4 | Run the card-info example to confirm the card is detected |
| 5 | Open the file in append mode and write a CSV header once |
| 6 | Log one line per reading: timestamp, then values |
| 7 | Flush after each write and close the file before removing the card |
Why log to an SD card at all
A sensor project that only shows live values on a serial monitor proves the sensor works. A sensor project that logs values for a week proves something about the world — and that is usually what the project is actually about. A weather station needs a week of temperature curves. A vibration study needs thousands of samples. A GPS tracker needs a route.
There are three ways to keep that data. Send it to the cloud over Wi-Fi, which needs a network and a server. Store it in the microcontroller's flash, which is small and wears out under constant writes. Or write it to an SD card, which holds gigabytes, costs almost nothing, and lets you pull the card out and open the file on any laptop. For a student project that runs offline, on a roof, in a field or on a moving robot, the SD card is usually the right answer — and it pairs well with the other two, as a backup when the network drops.
The module: what you are actually buying
An SD card module is a small breakout board with a card slot, a 3.3 V regulator and — on the better ones — a level shifter. Two facts about SD cards decide which module you need.
First, SD cards run on 3.3 V logic. An ESP32 is a 3.3 V board, so its pins connect directly. An Arduino Uno is a 5 V board, so its 5 V signals must be shifted down to 3.3 V before they reach the card, or the card can be damaged. Most Uno-sized modules include the level shifter on board; the bare-bones 3.3 V-only modules do not. If your module has a 5 V pin and a 3.3 V pin, it has the shifter — power it from 5 V on a Uno, from 3.3 V on an ESP32.
Second, the card talks over SPI, the same four-wire bus as many sensors and displays. That means the module shares the MOSI, MISO and SCK lines with other SPI devices, and each device gets its own chip-select (CS) pin. Keep that in mind when you plan pins: the card is one more SPI device, not a separate interface.
Buy a micro SD module (most cards sold today are micro SD, often with a full-size adapter) and a Class 10 card of 8 GB or 16 GB. Bigger cards work, but a logger that writes a few hundred kilobytes a day will never fill 8 GB — capacity is not the constraint, reliability is.
Wiring: Uno and ESP32
Arduino Uno
| Module pin | Uno pin |
|---|---|
| VCC | 5 V |
| GND | GND |
| MOSI | 11 |
| MISO | 12 |
| SCK | 13 |
| CS | 10 (or any digital pin) |
On the Uno, pins 11–13 are the hardware SPI pins; do not move them to other pins unless you are using software SPI, which is slower and rarely worth it. CS can be any free digital pin — pin 10 is the convention because the example sketches use it.
ESP32 (Arduino core)
| Module pin | ESP32 pin |
|---|---|
| VCC | 3.3 V (or VIN/5 V if the module has its own regulator) |
| GND | GND |
| MOSI | 23 |
| MISO | 19 |
| SCK | 18 |
| CS | 5 (or any free GPIO) |
The ESP32 also has a faster native interface, SD_MMC, which uses dedicated pins and 1-bit or 4-bit mode instead of SPI. It is noticeably faster — useful if you log at high speed — but it takes over specific pins, so use plain SPI mode first and switch only when speed forces you to. The code in this guide uses SPI mode, which works on both boards with small changes.
If the card is not detected and the wiring looks right, lower the SPI speed. Long jumper wires and breadboard connections are noisy, and a card that fails at the default speed often works at 1 MHz. On the ESP32 you can pass the speed to begin: SD.begin(5, SPI, 1000000) starts the card at 1 MHz on CS pin 5.
Format the card: FAT32 and the 8.3 filename trap
The Arduino SD library reads FAT16 and FAT32 filesystems. Format the card as FAT32 — cards up to 32 GB format to FAT32 cleanly in Windows, macOS and Linux. Do not use exFAT: the standard SD library cannot read it, and the card will simply report as not present. If your card is 64 GB or larger it may arrive formatted as exFAT; reformat it to FAT32 with a formatting tool before use.
Then comes the trap that wastes more student evenings than any other in this guide: on the Arduino Uno, filenames must follow the old 8.3 format — at most 8 characters for the name, a dot, and at most 3 for the extension, with no spaces or special characters. DATA.CSV and LOG01.TXT work. temperature-log.csv fails silently: SD.open returns nothing, no error is printed, and the sketch carries on logging into the void. On the ESP32, long filenames are fine, so code copied from an ESP32 example to a Uno fails for exactly this reason. Keep Uno filenames short and uppercase: LOG01.CSV, TEMP.CSV, GPS01.CSV.
First test: write and read a file
Before any sensor is involved, prove the card works with the simplest possible sketch. This is the same shape on both boards — only the CS pin differs.
#include <SPI.h>
#include <SD.h>
const int CS_PIN = 10; // Uno: 10. ESP32: 5
void setup() {
Serial.begin(115200);
while (!Serial) { }
if (!SD.begin(CS_PIN)) {
Serial.println("Card failed or not present");
return;
}
Serial.println("Card initialised");
File f = SD.open("TEST.TXT", FILE_WRITE);
f.println("hello, sd card");
f.close();
File r = SD.open("TEST.TXT");
while (r.available()) {
Serial.write(r.read());
}
r.close();
}
void loop() { }
If the serial monitor shows "Card initialised" followed by "hello, sd card", the whole chain — wiring, format, library — works. If it shows "Card failed", check in this order: card seated fully, FAT32 format, CS pin matches the code, power (the module needs a stable 3.3 V; a weak supply is a common cause), and SPI speed.
The logging sketch: CSV with timestamps
A real logger writes one line per reading. The sketch below reads a DHT22 temperature and humidity sensor every 10 seconds and appends a line to LOG01.CSV. It is written for the ESP32; the Uno version differs only in the CS pin, the filename rules, and the timestamp source (see the next section).
#include <SPI.h>
#include <SD.h>
#include <DHT.h>
#define DHTPIN 4
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
const int CS_PIN = 5;
void logLine(const char* line) {
File f = SD.open("/LOG01.CSV", FILE_APPEND);
if (!f) {
Serial.println("open failed");
return;
}
f.println(line);
f.flush();
f.close();
}
void setup() {
Serial.begin(115200);
dht.begin();
if (!SD.begin(CS_PIN)) {
Serial.println("Card failed");
while (true) { }
}
if (!SD.exists("/LOG01.CSV")) {
logLine("time,temp_c,humidity_pct");
}
}
void loop() {
float t = dht.readTemperature();
float h = dht.readHumidity();
if (isnan(t) || isnan(h)) {
Serial.println("sensor read failed");
} else {
char line[64];
snprintf(line, sizeof(line), "%lu,%.1f,%.1f", millis(), t, h);
logLine(line);
}
delay(10000);
}
Three details deserve attention.
Append, not write. On the ESP32 Arduino core, opening a file with FILE_WRITE truncates it — every restart wipes yesterday's data. FILE_APPEND adds to the end. This is the single most painful difference between the Uno and ESP32 SD libraries, and the cause of most "my log file is empty every morning" reports. Use FILE_APPEND for logging on the ESP32.
Flush and close every line. Data written to a file sits in a buffer before it reaches the card. If the power dies while the buffer is unflushed, the last lines are lost and the file can be corrupted. flush() pushes the buffer to the card; close() does the same and releases the file. Opening, writing, flushing and closing per line costs a little time and a little power, but for a reading every 10 seconds it is the right trade — a logger that loses its last hour of data when the battery dies has failed at its one job.
The header line. The if (!SD.exists(...)) check writes the column header only when the file is new. Without it, every restart adds another header row in the middle of the data, which breaks the spreadsheet import later.
Timestamps: millis, RTC or NTP
A log without timestamps is a list of numbers with no story. There are three ways to stamp each line, and the right one depends on the board.
millis() — milliseconds since the board started — is free and always available. It is enough when you only need the gap between readings, but it resets to zero on every restart and it drifts by seconds per day. Use it for short bench tests, not for a week-long deployment.
An RTC module (DS3231) is the standard answer for an Arduino Uno, which has no clock of its own. The DS3231 keeps time on a coin cell even when the main power is off, is accurate to a couple of minutes a year, and costs less than a sensor. Wire it over I2C, read the date and time, and write a real timestamp such as 2026-11-16T10:00:00 at the start of each line.
NTP over Wi-Fi is the standard answer for the ESP32. If the board connects to Wi-Fi anyway, fetch the time once at startup with configTime() and use getLocalTime() for each line. No extra hardware, and the clock is as accurate as the network. If the logger runs offline, fall back to the DS3231.
Whichever you choose, write timestamps in the same ISO-style format on every line. Mixed formats — millis() on some lines, clock time on others — make the analysis step miserable.
How much data will you actually collect?
Do the arithmetic before the deployment, not after the card fills. Take one line of the log above:
2026-11-16T10:00:00,24.5,61.2
That is 35 characters plus a newline, roughly 36 bytes per line. Logging every 10 seconds gives 6 lines a minute, 360 an hour, and 8,640 a day — about 311,000 bytes, or roughly 0.3 MB per day. An 8 GB card holds that rate for more than 25,000 days. Capacity is never the problem for a slow sensor logger; the card will corrupt, wear out or be lost long before it fills.
The arithmetic changes at high speed. Logging a vibration sensor at 100 readings a second with 40 bytes per line is 4,000 bytes a second, about 345 MB a day. Now the card fills in about three weeks, the write speed matters, and buffering in RAM before writing in blocks becomes worth doing. For most student loggers — temperature, humidity, light, GPS once a second — the slow case applies, and simple append-per-line code is fine.
Reading the data back: CSV to chart in Python
Pull the card, copy the CSV to your laptop, and the analysis is a few lines of Python with pandas and matplotlib:
import pandas as pd
df = pd.read_csv("LOG01.CSV", parse_dates=["time"])
print(df.head())
print(df.describe())
df.plot(x="time", y=["temp_c", "humidity_pct"])
Check the data before you chart it: missing lines where the sensor read failed, a header row repeated mid-file after a restart, or a timestamp jump where the board rebooted. Those artefacts are normal in a real deployment and worth a sentence in your report — they show you looked at the data instead of pasting a clean chart. The CSV format is the reason this whole approach is convenient: Excel, Google Sheets, Python and MATLAB all open it without conversion.
SD_MMC vs SPI on the ESP32
The ESP32 offers a second way to talk to a card: the SD_MMC peripheral, which uses the native SD protocol in 1-bit or 4-bit mode instead of SPI. It is several times faster than SPI mode and is the right choice when you log at high speed or write large files. The trade-off is pins: SD_MMC takes over specific GPIOs, so it can clash with other peripherals on a crowded board. Start with SPI mode — it works, it is portable between boards, and for a reading every few seconds the speed difference is irrelevant. Switch to SD_MMC only when a measurement shows SPI mode is too slow.
6 mistakes students make with SD card logging
- Formatting as exFAT. The standard library cannot read it; the card reports as absent. Format FAT32.
- Long filenames on the Uno. The 8.3 rule fails silently —
SD.openreturns nothing and the sketch logs into the void. - Using FILE_WRITE on the ESP32. It truncates the file on every open. Log with FILE_APPEND.
- Never flushing. A power cut loses the buffered lines and can corrupt the file. Flush and close every line.
- No timestamp plan.
millis()resets on reboot. Add an RTC or NTP before the deployment, not after. - Removing the card while logging. Always stop the logger or power the board down first. A card pulled mid-write is the most common cause of a corrupted log.
FAQ
How big a card do I need?
For a slow sensor logger, 8 GB is far more than enough — the worked example above uses about 0.3 MB a day. Buy 8 GB or 16 GB, Class 10, from a known brand. Avoid very large cards: 64 GB and up often arrive formatted as exFAT.
Can I use the same card for logging and for an ESP32-CAM?
Yes, but not at the same time from two devices. One board owns the card. If the camera and the logger are the same ESP32, they share the card fine — just use different filenames.
Why does my file have gaps?
Usually a failed sensor read (the sketch skips the line, as it should), a power dip that rebooted the board, or a card write that took longer than the logging interval. Check the timestamp column for jumps; a jump of one interval is a missed reading, a jump back to zero is a reboot.
Is an SD card better than sending data to the cloud?
Different jobs. The card is best when the deployment is offline, remote or temporary, and when you want the raw data in your hands. The cloud is best when you need live access or alerts. Many good student projects do both: log to the card always, and upload when Wi-Fi is available.
Can I log to the ESP32's internal flash instead?
Yes, with LittleFS or SPIFFS, for small amounts of data such as settings or a few hundred readings. Flash wears out under constant writes and holds far less than a card, so it is a poor choice for a long deployment.
My card works on the Uno but not the ESP32 — why?
Check three things: the CS pin in the code matches the wiring (ESP32 examples use GPIO 5, Uno examples use pin 10), the filename length (long names are fine on the ESP32, so this is rarely it), and FILE_APPEND vs FILE_WRITE — an ESP32 sketch that opens with FILE_WRITE appears to work but wipes the file each time.
Limitations
- SD cards are not real-time storage: a single write can take tens of milliseconds, so very high-speed logging needs RAM buffering and block writes.
- Cards corrupt on power loss mid-write; flush per line and use a stable supply, but accept that a deployment can still lose its last few lines.
- The standard SD library supports FAT16/FAT32 only — no exFAT, and no long filenames on the Arduino Uno.
- A card is a physical object: it can be lost, stolen or damaged, and it holds your only copy of the data. Copy the CSV off the card regularly during a long deployment.
- Cheap unbranded cards fail sooner and lie about their capacity; buy a known brand for anything that runs longer than a day.
Need this in your project?
If you are building a sensor logger — a weather station, a vibration study, a GPS tracker — and you want the logging, timestamps and data analysis built and working, message Projectech on WhatsApp at wa.me/918275719193 with your sensor list, how long it must log for, and your deadline. The reply is a quotation stating the scope, price and delivery timeline.