Categories: ESP32 Firmware Guide

SD Card operations on ESP32

SD card or Secure Digital card can store and retrieve data locally. An SD card is a non-volatile memory card used widely in portable devices, such as mobile phones, digital cameras, GPS navigation devices, and tablet computers. Micro-SD cards are also available now. It can store gigabytes of data in a small size.

The SD card library supports both FAT32 and FAT16 file systems. The communication between the ESP32 and SD Card uses standard SPI interfaces. This bus type supports only 3.3V interfaces. Which has SPI buses MISO, MOSI, SCK (CLK) and a slave select signal pin, SS.
Here using the libraries are SD.h and SPI.h

#include <SPI.h>
#include <SD.h>

Including SD.h automatically create a global “SD” object which can be interacted with in a similar manner to other standard global objects like “Serial”.
In the setup,SD.begin( ) names pin 5 as the SS pin and open a new file with SD.open( ) named “test.txt”.

if (!SD.begin(5)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

First, you need to open the file you want to write to the file with a FILE_WRITE parameter.FILE_WRITE enables read and write access to the file, starting at the end.

  myFile = SD.open("test.txt", FILE_WRITE);

If the file opened we can write in the file.

if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");

To read the file re-open the specified file. It will return false if it fails to open the file, so check myFile before using it. The “read” function reads the file line by line, so you will have to use a while loop until it fails to reach the end of the file. Now you can write to the file using this.

myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");
    while (myFile.available()) {
      Serial.write(myFile.read());

In this example though, immediately close the file by calling myFile.close( ).
Note that you need to close the file after writing to it. Also, you can only open one file at a time, if you want to open the next file, you need to close the current file first.

    myFile.close();

After checking to make sure the file exists with SD.exist ( ).

if (SD.exists("test.txt")) {
// test.txt exists
 }
else {
// test.txt doesn't exist
}

To delete the file from the card with SD.remove( ).

 SD.remove("test.txt");

You can open the file in your operating system by inserting the card. You will see one line for each time the sketch ran.

Share