ESP32 writing file to SD card

In this tutorial we will learn how to connect the ESP32 to a SD card and write a file to it.

Introduction

In this tutorial we will learn how to connect the ESP32 to a SD card and write a file to it.

We will focus on the actual code to interact with the SD card and not on how to do the wirings, since there are multiple approaches that can be followed (using a board with a built in SD card adapter, connecting to an external adapter, etc..).

In my case, I’m using a HW-818 ESP32 board model, which can be bought at eBay for around 10 Euros (link here). This board contains a SD card socket that we can use to get started right away, without the need for additional electronics.

Nonetheless, take in consideration that there are two libraries available in the Arduino core to interact with a SD card: the SD and SD_MMC. You can read the difference about them here. For more details, you can also consult the Espressif documentation about the lower level drivers.

So, depending on your hardware configuration, you should choose the correct one. For the board I’m using, I need to include the SC_MMC library.

The code

We will start the code by including the SD_MMC.h library. This library, included in the Arduino core, allows us to interact with the the SD card connected to the ESP32.

#include "SD_MMC.h"

Then, we will move to the Arduino setup function. We will start, as usual, by opening a serial connection. This way, we can print some outputs from our program to the serial port.

Serial.begin(115200);

After this, we will mount the SD card. Only after this procedure we can start interacting with it. To mount the SD card, we need to call the begin method on the SD_MMC extern variable. This procedure was already covered in more detail on this previous post.

Note that this method returns a Boolean value indicating if the procedure was successful or not. Naturally, if the mounting procedure fails, we shall not try to write content to the SD card, as it won’t work.

So, we will use the returning value of the begin method call for error checking.

if(!SD_MMC.begin()){
    Serial.println("Failed to mount card");
    return;
}

Next, we will take care of opening a file in writing mode. But before we move into the actual code, we will analyze the SD_MMC extern variable in more detail.

This variable, which becomes available after including the SD_MMC.h library, is an object of class SDMMCFS. This class inherits from the FS class, which is a file system wrapper class. This means we can interact with the SD_MMC extern variable in a very similar way like we did when interacting with the SPIFFS file system, in previous tutorials.

So, to create a new file, we need to open it with a call to the open method on the SD_MMC variable. This method receives as first argument the name of the file and as second the opening mode.

For our testing scenario, we will create a file called “/test.txt“. Additionally, we will be opening a file to write content to it. So, we want to open it in write mode. Thus, as second argument of the open method, we pass the constant FILE_WRITE (value defined here).

It’s important to take in consideration that the file doesn’t need to exist before we call this method. So, this method call will take care of the file creation.

As output, the open method returns an object of class File. We will store it in a variable, so we can write content to it below.

File file = SD_MMC.open("/test.txt", FILE_WRITE);

Before we proceed with the writing operation, we will do an error check to confirm the file was correctly opened. The File class overloads the C++ Boolean operator. Thus, we can use a simple IF condition to check if it was correctly opened. If not, we will print an error message and finish our program, since it won’t be possible to write content to the file.

if(!file){
    Serial.println("Opening file failed");
    return;
}

In case the opening procedure works, we can then write content to the file. To do so, we can simply use the print method, passing as input a string with the content to write. Note that this method returns as output the number of bytes written to the file, which we can use for a simple error checking.

if(file.print("Test file write")){
    Serial.println("File write success");
} else {
    Serial.println("File write failed");
}

To finalize our code, we will call the close method on our file object.

file.close();

The complete code can be seen below. The main loop was left empty since all our application was implemented in the Arduino setup function.

#include "SD_MMC.h"
 
void setup(){
   
    Serial.begin(115200);
     
    if(!SD_MMC.begin()){
        Serial.println("Failed to mount card");
        return;
    }

    File file = SD_MMC.open("/test.txt", FILE_WRITE);
    
    if(!file){
        Serial.println("Opening file failed");
        return;
    }
    
    if(file.print("Test file write")){
        Serial.println("File write success");
    } else {
        Serial.println("File write failed");
    }

    file.close();
}
 
void loop(){}

Testing the code

To test the code, simply compile it and upload it to your ESP32, using the Arduino IDE. Once the procedure finishes, open the IDE serial monitor.

You should get an output like figure 1. As can be seen, the file was successfully written to the SD card.

Output of the program, showing the success message.
Figure 1 – Output of the program, showing the success message.

1 thought on “ESP32 writing file to SD card”

Leave a Reply

Discover more from techtutorialsx

Subscribe now to keep reading and get access to the full archive.

Continue reading