SD card with an ESP32

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.

Duration :
Difficulty :
Documentation completed: 100% 100
Created by:  Alban Petit

Introduction

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:

  • Understand the SPI protocol used by the SD card
  • Add an SD socket directly to a PCB with the ESP32
  • Read and write files with the SD.h library
  • Record data continuously (datalogger)
  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.


The SPI protocol

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

Default SPI pins (SPI2)

Function ESP32-S3 GPIO
SCK GPIO 18
MISO GPIO 19
MOSI GPIO 11
CS GPIO 5
  Customisable SPI pins

On the ESP32-S3, the SPI bus can be assigned to any pins with SPI.begin(SCK, MISO, MOSI, CS). The pins given here are the ones used in this tutorial. For a PCB, you can choose other GPIOs to suit the routing.


Adding it to a PCB

Choosing the socket

There are two types of retention mechanism for SD sockets:

  • Push-push: the card locks when pressed, and a second press ejects it
  • Push-pull: the card slides in freely and is removed by pulling it

For embedded use (risk of vibration), prefer a push-push socket with a lock.

  FAT32 format required

The ESP32 SD.h library only supports the FAT32 file system. Format your SD card as FAT32 before use. Cards > 32 GB are often formatted as exFAT by default: they must be manually reformatted as FAT32 (use the official tool SD Card Formatter).

Wiring diagram

               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  ─┘

Pull-up resistors

The SPI lines need pull-up resistors to 3.3V:

Pull-ups on MISO and CS

Add a 10kΩ resistor to 3.3V on the following lines:

  • MISO: avoids a floating state when no card is inserted (the SPI bus would be undefined)
  • CS: keeps Chip Select inactive (high) at start-up, before the GPIO is configured

SCK and MOSI are actively driven by the ESP32 from start-up and do not need pull-ups.

Decoupling capacitors

Power supply decoupling

Place the following capacitors between VDD and GND of the socket, as close as possible to the VDD pin:

  • 100nF ceramic: filters the high-frequency noise generated by SPI transitions
  • 10µF ceramic or tantalum: absorbs the current peaks when the card initialises (up to 200mA peak)

Both capacitors must be placed as close as possible to the socket on the PCB, with a short GND return path.

Card Detect (CD) pin

Detecting card insertion

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);

Checklist before powering up

Checks before the first test

Before powering your PCB for the first time:

  • Visually check the solder joints of the socket (no short circuit between pads)
  • Check continuity between the socket GND and the ESP32 GND
  • Check continuity between the socket VDD and 3.3V
  • Check that the decoupling capacitors are fitted (100nF + 10µF)
  • Check the pull-up resistors on MISO and CS
  • Insert an SD card formatted as FAT32
  • Measure 3.3V on VDD before powering the ESP32

Code

PlatformIO project configuration

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

Code 1: Initialisation and card information

#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() {}

Code 2: Reading and writing files

#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() {}
  Always close files

The SD.h library uses an internal cache. If you leave out file.close(), the data may not be physically written to the card if power is lost. Always call file.close() after each write.

Code 3: Datalogger (continuous recording)

#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.");
    }
  }
}

Troubleshooting

The SD card is not detected

Check the SPI wiring

Wiring mistakes are the most common cause. Check that:

  • MISO and MOSI are not swapped (a very common mistake)
  • CS is connected to the GPIO declared in the code
  • Ground is common to the ESP32 and the SD socket

Lower the SPI speed

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

Check the FAT32 format

The SD.h library only supports FAT32.

  • Windows: right-click → Format → FAT32
  • macOS: Disk Utility → MS-DOS (FAT)
  • Linux: sudo mkfs.fat -F 32 /dev/sdX1

Cards > 32 GB need the SD Card Formatter tool to force FAT32.

The ESP32 restarts while accessing the SD card

Power supply problem

Accesses to the SD card generate current peaks (up to 200mA). If the power supply is insufficient, the ESP32 may restart or reset:

  • Check that the 10µF capacitor is fitted on the socket VDD
  • Check that the power source can supply at least 500mA continuously

Resources


Conclusion

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.

Key points to remember

  • SPI2 bus: SCK=18, MISO=19, MOSI=11, CS=5, initialise with SPI.begin(18, 19, 11, 5)
  • FAT32 format required for the SD.h library
  • 10kΩ pull-ups on MISO and CS are essential on a PCB
  • Decoupling: 100nF + 10µF as close as possible to the socket VDD
  • Always call file.close() after a write

Going deeper

  • Pair the SD card with an RTC module (DS3231) to timestamp your measurements
  • Use the ArduinoJson library to store configuration files in JSON
  • Explore SD_MMC.h for higher speeds over the ESP32’s native SDMMC bus
  Well done!

Your ESP32 can now read and write files on an SD card. It is an essential building block for any datalogging or configuration storage project.

Need help?