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 |
---|---|---|
|
Mount point path |
Specifies the prefix of the path where the SD card is mounted to VFS. |
|
Host controller configuration |
Defines the initialization parameters of the SDMMC or SDSPI host, usually generated by the |
|
Slot configuration |
Specifies the configuration of the SD card slot, including pin mapping and bus width, usually generated by the |
|
Mount configuration |
A structure that controls the way the file system is mounted. |
|
Card information structure pointer |
Output parameter, returns a pointer to the initialized |
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 |
---|---|---|
|
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. |
|
Corresponding slot number |
Choose according to reality, usually 0 or 1. |
|
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. |
|
Controller I/O voltage |
Commonly used 3.3 V, set to 0.0 when using the default value. |
|
Initialize the host driver |
Must provide function implementation. |
|
Set bus width |
Function pointer, used to set the bus width according to the configuration. |
|
Execute SD/MMC command |
Specify the core operation function. |
|
Set card clock |
Used in high-speed mode or at specific frequencies. |
|
Single command timeout time |
Set according to requirements, or use the default value. |
Common Flags |
Flag Description |
---|---|
|
Supports 1-line SD/MMC. |
|
Supports 4-line SD/MMC. |
|
Supports 8-line MMC (SD card does not support 8 lines). |
|
Supports SPI protocol. |
|
Supports DDR mode. |
|
Indicates that the |
|
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 signal pin |
Used for SD/MMC clock, ensure GPIO matches the actual hardware wiring. |
|
CMD signal pin |
Used for SD card command transmission, ensure GPIO matches the actual hardware wiring. |
|
Data line pins |
Select the number of pins needed according to the data width, where |
|
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 |
|
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 |
|
Bus width |
Confirm the bus width supported by the hardware, commonly one-line or four-line. |
|
Flags controlling SD card slot functions |
Set according to application requirements, common flags are shown in the table below. |
Common Flags |
Flag Description |
Flag Explanation |
---|---|---|
|
Enable internal pull-up (for debugging/example purposes only) |
It is recommended to still ensure signal reliability through external pull-up resistors. |
|
Write protection polarity |
Set to 1 indicates high level effective, set to 0 indicates low level effective. |
|
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 fails |
When set to |
|
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 |
The allocation unit size of the FAT file system affects storage efficiency and performance, common settings are 16 KB or 32 KB. |
|
Partition label |
Used to specify the partition to mount, usually set to |
|
Pointer to card information structure |
Output parameter, returns a pointer to the initialized |
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;