Logic level compatibility
The ESP32 uses 3.3V logic. SD cards also operate at 3.3V, so no level shifter is needed. A direct connection is possible with no component in between.
Adding an SD socket to a PCB and reading/writing files
SD card with an ESP32
This tutorial explains how to add an SD socket to a PCB with an ESP32, wire the SPI bus correctly and read or write files with the SD.h library.
Machines/Tools:
An SD card is a simple, inexpensive way to add persistent storage to an embedded project. Paired with the ESP32, it can record sensor measurements, event logs, configuration files or even audio data.
In this tutorial, you will learn to:
SD.h libraryThe SD card communicates over the SPI (Serial Peripheral Interface) protocol, a 4-wire synchronous serial bus:
| Signal | Role |
|---|---|
| SCK (Clock) | Clock generated by the master (ESP32) |
| MOSI (Master Out Slave In) | Data sent by the ESP32 to the card |
| MISO (Master In Slave Out) | Data sent by the card to the ESP32 |
| CS (Chip Select) | Slave select (active low) |
The ESP32-S3 has two usable SPI buses: SPI2 (the default) and SPI3.
| Function | ESP32-S3 GPIO |
|---|---|
| SCK | GPIO 18 |
| MISO | GPIO 19 |
| MOSI | GPIO 11 |
| CS | GPIO 5 |
There are two types of retention mechanism for SD sockets:
For embedded use (risk of vibration), prefer a push-push socket with a lock.
ESP32
GPIO18 ─────────── SCK ─┐
GPIO19 ─────────── MISO ─┤
GPIO11 ─────────── MOSI ─┤ SD socket
GPIO5 ─────────── CS ─┤
3.3V ── 10kΩ ─── MISO ─┤ (pull-up)
3.3V ── 10kΩ ─── CS ─┤ (pull-up)
3.3V ─────────── VDD ─┤
GND ─────────── GND ─┘
The SPI lines need pull-up resistors to 3.3V:
Add a 10kΩ resistor to 3.3V on the following lines:
SCK and MOSI are actively driven by the ESP32 from start-up and do not need pull-ups.
Place the following capacitors between VDD and GND of the socket, as close as possible to the VDD pin:
Both capacitors must be placed as close as possible to the socket on the PCB, with a short GND return path.
Most SD sockets expose a CD (Card Detect) pin connected to an internal mechanical switch. This switch closes to ground when a card is inserted.
Connect CD to an ESP32 GPIO with a 10kΩ pull-up resistor to 3.3V.
If detection is not needed in your application, leave the CD pin unconnected.
In the code, you can watch this state to detect insertion or removal:
bool cardPresent = (digitalRead(CD_PIN) == LOW);
Before powering your PCB for the first time:
The SD.h library is included in the Arduino framework for ESP32: no extra dependency is needed.
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
#include <Arduino.h>
#include <SD.h>
#include <SPI.h>
#define CS_PIN 5
void setup() {
Serial.begin(115200);
delay(500);
Serial.println("Initialising the SD card...");
// On the ESP32-S3, initialise the SPI bus with explicit pins
SPI.begin(18, 19, 11, CS_PIN); // SCK, MISO, MOSI, CS
if (!SD.begin(CS_PIN, SPI)) {
Serial.println("Error: SD card not detected or not initialised.");
Serial.println("Check the wiring and the FAT32 formatting.");
while (true) delay(1000);
}
Serial.println("SD card initialised successfully!");
uint8_t cardType = SD.cardType();
Serial.print("Card type: ");
if (cardType == CARD_MMC) Serial.println("MMC");
else if (cardType == CARD_SD) Serial.println("SDSC");
else if (cardType == CARD_SDHC) Serial.println("SDHC");
else Serial.println("UNKNOWN");
uint64_t cardSize = SD.cardSize() / (1024 * 1024);
Serial.printf("Size : %llu MB\n", cardSize);
Serial.printf("Free space : %llu MB\n", (SD.totalBytes() - SD.usedBytes()) / (1024 * 1024));
}
void loop() {}
#include <Arduino.h>
#include <SD.h>
#include <SPI.h>
#define CS_PIN 5
void writeFile(const char* path, const char* message) {
File file = SD.open(path, FILE_WRITE);
if (!file) {
Serial.printf("Error: cannot open %s for writing\n", path);
return;
}
file.print(message);
file.close(); // mandatory flush
}
void appendFile(const char* path, const char* message) {
File file = SD.open(path, FILE_APPEND);
if (!file) return;
file.print(message);
file.close();
}
void readFile(const char* path) {
File file = SD.open(path);
if (!file) {
Serial.printf("Error: file %s not found\n", path);
return;
}
while (file.available()) {
Serial.write(file.read());
}
file.close();
}
void setup() {
Serial.begin(115200);
delay(500);
SPI.begin(18, 19, 11, CS_PIN); // SCK, MISO, MOSI, CS
if (!SD.begin(CS_PIN, SPI)) {
Serial.println("Error: SD card not initialised.");
while (true) delay(1000);
}
writeFile("/log.txt", "Start-up\n");
appendFile("/log.txt", "Measurement 1: 23.5°C\n");
appendFile("/log.txt", "Measurement 2: 24.1°C\n");
readFile("/log.txt");
}
void loop() {}
#include <Arduino.h>
#include <SD.h>
#include <SPI.h>
#define CS_PIN 5
const char* LOG_FILE = "/data.csv";
const unsigned long LOG_INTERVAL = 1000; // ms
unsigned long lastLog = 0;
float readTemperature() {
// Replace with the reading of your sensor
return 20.0f + (millis() / 1000.0f) * 0.1f;
}
void setup() {
Serial.begin(115200);
delay(500);
SPI.begin(18, 19, 11, CS_PIN); // SCK, MISO, MOSI, CS
if (!SD.begin(CS_PIN, SPI)) {
Serial.println("Error: SD card not initialised.");
while (true) delay(1000);
}
// Create the CSV header if the file does not exist yet
if (!SD.exists(LOG_FILE)) {
File f = SD.open(LOG_FILE, FILE_WRITE);
if (f) {
f.println("timestamp_ms,temperature_C");
f.close();
}
}
Serial.println("Datalogger started.");
}
void loop() {
unsigned long now = millis();
if (now - lastLog >= LOG_INTERVAL) {
lastLog = now;
float temp = readTemperature();
String line = String(now) + "," + String(temp, 2);
File f = SD.open(LOG_FILE, FILE_APPEND);
if (f) {
f.println(line);
f.close();
Serial.println("Log: " + line);
} else {
Serial.println("Write error.");
}
}
}
Wiring mistakes are the most common cause. Check that:
Some SD cards do not support high SPI speeds. Initialise with a lower frequency:
SPI.begin(18, 19, 11, CS_PIN);
SD.begin(CS_PIN, SPI, 4000000); // 4 MHz instead of 25 MHz
If it works at low speed, the card or the PCB routing is to blame (tracks too long, no decoupling).
The SD.h library only supports FAT32.
sudo mkfs.fat -F 32 /dev/sdX1Cards > 32 GB need the SD Card Formatter tool to force FAT32.
Accesses to the SD card generate current peaks (up to 200mA). If the power supply is insufficient, the ESP32 may restart or reset:
You now know how to add an SD socket to a PCB with the ESP32 and work with the data through the SD.h library.
SPI.begin(18, 19, 11, 5)SD.h libraryfile.close() after a write