General Steps

[中文]

Note

This document is automatically translated using AI. Please excuse any detailed errors. The official English version is still in progress.

This document summarizes the general implementation process of SD card storage in ESP-IDF, covering its basic description, initialization steps, and related execution process.

By mastering the content of this document, developers can quickly understand the key logic related to SD card storage, providing a unified reference for subsequent example learning.

Overview of SD Card Storage

SD (Secure Digital) card is a widely used non-volatile storage medium, commonly used in embedded systems, digital cameras, mobile phones, and other devices for storing data, files, and programs. It is small in size, low in power consumption, and expandable in capacity.

In embedded systems, the main uses of the SD card storage module include:

  • Data storage: Save data collected by sensors, log information, or user files.

  • Program expansion: Store application resources, such as pictures, audio, configuration files.

  • File system support: Access data through the FAT file system, convenient for exchanging data with PCs or other devices.

  • Firmware upgrade: Store firmware images on the card for OTA or manual upgrades.

Key Technical Points of SD Card Storage

When using the SD card storage module, some core knowledge points need to be mastered to ensure the correct initialization of the card, stable reading and writing, and efficient use. This section will explain key points such as interface mode, bus configuration, file system, initialization process, error handling, etc.

Interface Mode

The SD card communicates with the main control chip through two interfaces: SPI mode and SD mode (also known as SDMMC mode).

SPI mode uses the standard SPI bus for data exchange. The communication protocol is simple and compatible, so almost all MCUs can support it, suitable for low-speed data access or resource-limited application scenarios. However, the transmission speed of SPI mode is limited and cannot meet the high-speed reading and writing needs of large-capacity data.

SD/SDMMC mode uses the built-in SD/MMC controller of ESP32 to directly access the storage card, which can use one or four data lines to transmit data in parallel, thereby achieving high-speed access.

The interface mode determines the data transmission speed, hardware connection method, and initialization parameters.

Bus Width

The bus width determines the degree of parallelism and speed of data transmission. The SD card can choose to work in one-line or four-line mode under SD mode.

  • One-line mode: Use a single data line (DAT0) for data transmission, simple hardware wiring, save pin resources, but the data transmission speed is lower, suitable for low-speed or simple applications.

  • Four-line mode: Use four data lines (DAT0–DAT3) to transmit data in parallel, the speed is about four times that of the single-line mode, but it occupies more pins and requires higher hardware layout.

Choosing the appropriate bus mode requires a balance between performance and pin resources, and the correct number of lines parameters must be set during initialization, otherwise, it may lead to read and write failures or poor performance. In ESP32, if SDMMC mode is used, the four-line mode is generally recommended for higher performance; if resources are limited or SPI mode is used, the one-line mode is usually adopted.

File System

The data on the SD card is usually managed through the FAT file system. The FAT file system provides directory and file management capabilities, making data access as convenient as on a regular computer. In ESP-IDF, the FAT file system is accessed through the FATFS interface, supporting operations such as file creation, reading, writing, and deletion.

Understanding the structure and mechanism of the file system is very important because file system mounting failures, abnormal power outages, or unsynchronized data can all lead to data corruption. Therefore, when designing applications, it is necessary to ensure that files are synchronized in time after read and write operations, or provide formatting or recovery strategies in abnormal situations. The reliability of the file system is directly related to the stability of the SD card module in the application.

Card Initialization

Before any read or write operation, the SD card must go through a complete initialization process:

  • Detect if the SD card is present: Determine whether the card has been inserted and identify the card type (SD, SDHC, SDXC, or MMC).

  • Configure bus parameters: Such as interface mode (SPI/SDMMC), clock frequency, and number of lines (1-bit/4-bit).

  • Mount the file system: Mount the FAT file system to a specified path for application access.

If initialization fails, it may be due to the card not being inserted, wiring errors, improper bus parameter configuration, or file system damage, so it is recommended to design reasonable error handling and retry mechanisms in the application.

Data Consistency and Error Handling

In practical applications, various abnormal situations may occur with the SD card, such as

  • Read/write failure: Due to hardware jitter, card aging, or communication abnormalities.

  • Card removal: Being pulled out during access, which will cause the mount to fail.

  • File system damage: Abnormal power off or unsynchronized data may damage the file structure.

To ensure data consistency, error detection and handling mechanisms must be implemented at the software level. Common practices include checking read/write return values, synchronizing (flushing) after important data is written, and remounting or formatting the card in exceptional situations.

For data-critical applications, such as log storage, sensor data collection, etc., the error handling strategy is particularly important as it directly affects system stability and data reliability.

Performance Optimization

The performance of the SD card is not only affected by the interface mode and the number of bus lines, but also closely related to the clock frequency, cache policy, and task access method.

  • Clock frequency: The SDMMC mode supports high-frequency access, and reasonably increasing the clock frequency in this mode can improve data transmission speed.

  • Cache and buffer: Using read/write cache can reduce the number of file system operations, thereby reducing latency and improving performance.

  • Multi-task access: In a multi-task environment, such as FreeRTOS, multi-task simultaneous access to the SD card requires the use of mutex or synchronization mechanisms to avoid data conflicts and resource contention.

Performance optimization can not only improve read/write speed but also ensure system stability under high load.

Speed Mode Configuration

When using an SD card, it is necessary to configure according to the bus and speed modes supported by the card to ensure the reliability and performance of data transmission. UHS-I (Ultra High Speed Phase I) is a high-speed bus specification for SD cards, which can provide higher transmission rates compared to ordinary SD modes. Common speed modes under UHS-I include SDR50 (Single Data Rate 50 MHz) and DDR50 (Double Data Rate 50 MHz).

SDR50 mode is a single data rate mode, where data is transmitted once at the rising edge of the clock, with a theoretical maximum transmission speed of about 50 MB/s. DDR50 mode is a double data rate mode, where data is transmitted once at both the rising and falling edges of the clock, with a theoretical maximum speed of up to 100 MB/s.

Detecting the speed modes supported by the SD card is crucial for controller configuration. Under different speed modes, the SD card requires corresponding controller configurations to ensure stable communication:

  • Clock configuration: The clock frequency and data transmission method of SDR50 and DDR50 are different, and the controller must adjust the clock and signal sampling according to the mode.

  • Data integrity: High-speed modes have stricter requirements for voltage, pull-up/pull-down resistors, and PCB wiring. Incorrect configuration may lead to read/write failures.

  • Performance optimization: If it is detected that the SD card supports high-speed mode, the corresponding mode can be enabled to improve data transmission performance, otherwise, it will fall back to the standard rate to ensure reliability.

..note:

Different chips may have different support for SD card speed modes. You can confirm the supported modes through the `ESP Chip & Module Selection Tool <https://products.espressif.com/#/product-selector?language=en&names=>` and configure the controller accordingly.

General Steps for SD Card Storage

When using an SD storage card, initialization and mounting are essential steps. ESP-IDF provides a variety of low-level APIs to complete operations such as host controller initialization, card recognition, file system mounting, and virtual file system registration. To simplify the process, ESP-IDF provides a one-stop convenience function esp_vfs_fat_sdmmc_mount(), which integrates the initialization of the underlying driver with the file system mounting step. Developers only need to call this function to complete the SD card initialization and file system mounting, without having to call multiple low-level APIs one by one.

This function plays an integrative control role in the initialization process, specifically including the following aspects:

  • Initialize the host controller: Configure the SDMMC or SDSPI host, establish communication between the ESP chip and the SD card hardware.

  • Detect and initialize the SD card: Automatically recognize the card type (such as SD, SDHC, SDXC), complete the reading and configuration of parameters such as capacity, transmission rate, etc.

  • Mount the FAT file system: Call the FATFS library to mount the file system, so that the SD card can be accessed as a storage medium.

  • Register VFS (Virtual File System): Register the FATFS file system to the VFS layer of ESP-IDF, the application program can directly use standard C file operations to access the files on the SD card.

When calling this function, several configuration parameters need to be passed in to control the mounting point, host and slot configuration methods, and mounting behavior. The parameter descriptions are as follows, referenced from FAT file system:

Input parameter

Parameter description

Parameter explanation

base_path

Mount point path

Specifies the prefix of the path where the SD card is mounted to VFS.

host_config

Host controller configuration

Defines the initialization parameters of the SDMMC or SDSPI host, usually generated by the SDMMC_HOST_DEFAULT() or SDSPI_HOST_DEFAULT() macro.

slot_config

Slot configuration

Specifies the configuration of the SD card slot, including pin mapping and bus width, usually generated by the SDMMC_SLOT_CONFIG_DEFAULT() or SDSPI_SLOT_CONFIG_DEFAULT() macro.

mount_config

Mount configuration

A structure that controls the way the file system is mounted.

out_card

Card information structure pointer

Output parameter, returns a pointer to the initialized sdmmc_card_t structure, which contains card capacity, CID/CSD information, etc., for subsequent operations.

With this function, the SD card initialization process is greatly simplified. Just configure each parameter according to the requirements to complete the card initialization and file system mounting, improving development efficiency and code readability.

Mount Point Path

The mount point path is used to specify the access location of the SD card in the Virtual File System (VFS). All file operations will use this path as a prefix. A common path is "/sdcard", after mounting, files can be accessed through paths like "/sdcard/filename.txt". When designing the mount point, ensure the path is unique to avoid conflicts with the system or other mount points, thereby ensuring the correctness of file system operations.

Host Controller Configuration

The host controller is configured through the sdmmc_host_t structure, which is used to define the communication parameters between the ESP chip and the SD card hardware, including clock frequency, DMA settings, and operating mode. The specific structure member descriptions are as follows:

Structure Member

Member Description

Member Configuration

flags

Protocol and bus width flags supported by the host

Set according to application requirements, at least set the supported bus width, common flags are shown in the table below.

slot

Corresponding slot number

Choose according to reality, usually 0 or 1.

max_freq_khz

Maximum frequency supported by the host

Initially, the default value (20000 kHz) can be used; if high-speed mode is required, it can be set to 40000 kHz.

io_voltage

Controller I/O voltage

Commonly used 3.3 V, set to 0.0 when using the default value.

init

Initialize the host driver

Must provide function implementation.

set_bus_width

Set bus width

Function pointer, used to set the bus width according to the configuration.

do_transaction

Execute SD/MMC command

Specify the core operation function.

set_card_clk

Set card clock

Used in high-speed mode or at specific frequencies.

command_timeout_ms

Single command timeout time

Set according to requirements, or use the default value.

Common Flags

Common Flags

Flag Description

SDMMC_HOST_FLAG_1BIT

Supports 1-line SD/MMC.

SDMMC_HOST_FLAG_4BIT

Supports 4-line SD/MMC.

SDMMC_HOST_FLAG_8BIT

Supports 8-line MMC (SD card does not support 8 lines).

SDMMC_HOST_FLAG_SPI

Supports SPI protocol.

SDMMC_HOST_FLAG_DDR

Supports DDR mode.

SDMMC_HOST_FLAG_DEINIT_ARG

Indicates that the deinit function carries the slot parameter.

SDMMC_HOST_FLAG_ALLOC_ALIGNED_BUF

Indicates that the internal allocation meets the DMA alignment requirements (512B).

For SDMMC mode, you can generate the default configuration through the SDMMC_HOST_DEFAULT() macro; for SDSPI mode, you can use the SDSPI_HOST_DEFAULT() macro to generate the configuration. When choosing the host type, consider the actual situation of the hardware interface, different modes have differences in speed and feature support.

Correct configuration of the host controller can ensure the stability and performance of data transmission.

Slot Configuration

The slot is configured through the structure sdmmc_slot_config_t, which is used to define the specific parameters of the SD card slot, including GPIO pin mapping and bus width (one-line or four-line mode). The specific structure member descriptions are as follows, referenced from SDMMC Host Driver:

Structure Member

Member Description

Member Configuration

clk

CLK signal pin

Used for SD/MMC clock, ensure GPIO matches the actual hardware wiring.

cmd

CMD signal pin

Used for SD card command transmission, ensure GPIO matches the actual hardware wiring.

D0 - D7

Data line pins

Select the number of pins needed according to the data width, where D0 is the least significant bit, and D7 is the most significant bit. Ensure GPIO matches the actual hardware wiring.

gpio_cd / cd

Card detection pin, accessible by two names

If using the SD card plug detection function, specify the actually connected GPIO; if not in use, set to GPIO_NUM_NC to indicate not connected.

gpio_wp / wp

Write protection signal, accessible by two names

If using the write protection function, specify the actually connected GPIO and set the write protection polarity flag; if not in use, set to GPIO_NUM_NC to indicate not connected.

width

Bus width

Confirm the bus width supported by the hardware, commonly one-line or four-line.

flags

Flags controlling SD card slot functions

Set according to application requirements, common flags are shown in the table below.

Common Flags

Common Flags

Flag Description

Flag Explanation

SDMMC_SLOT_FLAG_INTERNAL_PULLUP

Enable internal pull-up (for debugging/example purposes only)

It is recommended to still ensure signal reliability through external pull-up resistors.

SDMMC_SLOT_FLAG_WP_ACTIVE_HIGH

Write protection polarity

Set to 1 indicates high level effective, set to 0 indicates low level effective.

SDMMC_SLOT_FLAG_UHS1

UHS-I mode

Set to 1 to enable UHS-I mode, which can improve high-speed transmission rate.

For SDMMC mode, you can use the SDMMC_SLOT_CONFIG_DEFAULT() macro to generate the default configuration; for SDSPI mode, you need to modify the GPIO pins according to the actual wiring, such as MISO, MOSI, CLK, and CS.

The slot configuration directly affects the data transmission efficiency and interface compatibility, so it should be adjusted according to the hardware design.

Mount Configuration

File mounting is configured through the structure esp_vfs_fat_sdmmc_mount_config_t, the behavior and limitations of file system mounting are important parameters to ensure the normal use of the file system. The specific structure member descriptions are as follows, referenced from FAT File System:

Structure Member

Member Description

Member Configuration

format_if_mount_failed

Format if mount fails

When set to true, if the file system mount fails, the function will first format the SD card and then try to mount again; when set to false, it will return an error directly when the mount fails.

max_files

Maximum number of files

Limits the number of files that can be opened at the same time, typically between 5 and 10, to prevent file handle exhaustion.

allocation_unit_size

Allocation unit size

The allocation unit size of the FAT file system affects storage efficiency and performance, common settings are 16 KB or 32 KB.

disk_status_check_enable

Partition label

Used to specify the partition to mount, usually set to NULL to use the default partition.

out_card

Pointer to card information structure

Output parameter, returns a pointer to the initialized sdmmc_card_t structure, which includes card capacity, CID/CSD information, etc., for subsequent operations.

Reasonable configuration of mount parameters can balance storage efficiency and data security, for example, the automatic formatting option should be turned off in scenarios where existing data needs to be preserved.

Pointer to Card Information Structure

This parameter is used to return a pointer to the initialized SD card information. The structure type is sdmmc_card_t. Through this structure, detailed information such as card capacity, CID, CSD, bus speed and type can be obtained, which is convenient for subsequent operations and debugging. When using, you need to first define the pointer variable and pass it into the function:

..code:

sdmmc_card_t *card;