ESP32学习笔记(44)——SD卡使用(SPI方式)

该博客介绍了如何在ESP32-LyraT V4.3开发板上通过SPI接口与SD卡进行通信,包括SPI总线初始化、挂载FAT文件系统、读写文件以及硬件连接等步骤。示例代码展示了如何使用ESP-IDF库进行文件操作,如创建、重命名和读取文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、简介

SD 卡(Secure Digital Memory Card) 在我们生活中已经非常普遍了,控制器对 SD 卡进行
读写通信操作一般有两种通信接口可选,一种是 SPI 接口,另外一种就是 SDIO 接口。
SDIO 全称是安全数字输入/输出接口,多媒体卡(MMC)、SD 卡、SD I/O 卡都有 SDIO 接口。
MMC 卡可以说是 SD 卡的前身,现阶段已经用得很少。

二、API说明

以下 SD SPI 主机接口位于 driver/include/driver/sdspi_host.h

2.1 SDSPI_HOST_DEFAULT

SDSPI_HOST_DEFAULT()
SD over SPI 驱动程序的默认sdmmc_host_t结构初始值设定项
使用 SPI 模式,最大频率设置为 20MHz。
“插槽”应由sdspi_host_init_device()设置。

2.2 SDSPI_DEVICE_CONFIG_DEFAULT

SDSPI_DEVICE_CONFIG_DEFAULT()
定义 SD SPI 设备默认配置的宏。

以下 SPI 主机接口位于 driver/include/driver/spi_common.h

2.3 spi_bus_initialize

2.4 spi_bus_free

以下 FAT 文件系统接口位于 fatfs/vfs/esp_vfs_fat.h

2.5 esp_vfs_fat_sdspi_mount

2.6 esp_vfs_fat_sdcard_unmount

以下 SDMMC 接口位于 sdmmc/include/sdmmc_cmd.h

2.7 sdmmc_card_print_info

三、编程流程

  1. SPI总线初始化
  2. esp_vfs_fat_sdspi_mount() 挂载文件系统
    • 使用FATFS库安装FAT文件系统(如果无法安装文件系统,则使用格式化卡);
    • 在VFS中注册FAT文件系统,以使用C标准库和POSIX函数。
  3. 打印有关SD卡的信息,例如名称、类型、容量和支持的最大频率。
  4. 使用fopen()创建一个文件,并使用fprintf()写入该文件。
  5. 重命名该文件。重命名之前,请使用stat()函数检查目标文件是否已存在,并使用unlink()函数将其删除。
  6. 打开重命名的文件进行读取,读回该行,并将其打印到终端。

四、硬件连接

我使用的是 ESP32-LyraT V4.3 开发板

SD卡只能使用3.3V的I/O电平。SPI模式下信号线要加10-100K的上拉电阻。

SPI信号线端口
MISOIO2
MOSIIO15
CLKIO14
CSIO13

五、示例代码

根据 examples\storage\sd_card 中的例程修改

/* SD card and FAT filesystem example.
   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

#include <stdio.h>
#include <string.h>
#include <sys/unistd.h>
#include <sys/stat.h>
#include "esp_err.h"
#include "esp_log.h"
#include "esp_vfs_fat.h"
#include "driver/sdspi_host.h"
#include "driver/spi_common.h"
#include "sdmmc_cmd.h"
#include "sdkconfig.h"

static const char *TAG = "example";

#define MOUNT_POINT "/sdcard"

// This example can use SDMMC and SPI peripherals to communicate with SD card.
// By default, SDMMC peripheral is used.
// To enable SPI mode, uncomment the following line:

// DMA channel to be used by the SPI peripheral
#define SPI_DMA_CHAN    1

// When testing SD and SPI modes, keep in mind that once the card has been
// initialized in SPI mode, it can not be reinitialized in SD mode without
// toggling power to the card.

// Pin mapping when using SPI mode.
// With this mapping, SD card can be used both in SPI and 1-line SD mode.
// Note that a pull-up on CS line is required in SD mode.
#define PIN_NUM_MISO 2
#define PIN_NUM_MOSI 15
#define PIN_NUM_CLK  14
#define PIN_NUM_CS   13

void app_main(void)
{
    esp_err_t ret;
    // Options for mounting the filesystem.
    // If format_if_mount_failed is set to true, SD card will be partitioned and
    // formatted in case when mounting fails.
    esp_vfs_fat_sdmmc_mount_config_t mount_config = {  // 文件系统挂载配置
        .format_if_mount_failed = true,                // 如果挂载失败:true会重新分区和格式化/false不会重新分区和格式化
        .max_files = 5,                                // 打开文件最大数量
        .allocation_unit_size = 16 * 1024
    };
    sdmmc_card_t* card;                        // SD / MMC卡信息结构
    const char mount_point[] = MOUNT_POINT;    // 根目录
    ESP_LOGI(TAG, "Initializing SD card");

    // Use settings defined above to initialize SD card and mount FAT filesystem.
    // Note: esp_vfs_fat_sdmmc/sdspi_mount is all-in-one convenience functions.
    // Please check its source code and implement error recovery when developing
    // production applications.
    ESP_LOGI(TAG, "Using SPI peripheral");

    sdmmc_host_t host = SDSPI_HOST_DEFAULT();
    spi_bus_config_t bus_cfg = {
        .mosi_io_num = PIN_NUM_MOSI,
        .miso_io_num = PIN_NUM_MISO,
        .sclk_io_num = PIN_NUM_CLK,
        .quadwp_io_num = -1,
        .quadhd_io_num = -1,
        .max_transfer_sz = 4000,
    };
    // SPI总线初始化
    ret = spi_bus_initialize(host.slot, &bus_cfg, SPI_DMA_CHAN);
    if (ret != ESP_OK) {
        ESP_LOGE(TAG, "Failed to initialize bus.");
        return;
    }

    // 这将初始化没有卡检测(CD)和写保护(WP)信号的插槽。
    // 如果您的主板有这些信号,请修改slot_config.gpio_cd和slot_config.gpio_wp。
    sdspi_device_config_t slot_config = SDSPI_DEVICE_CONFIG_DEFAULT();
    slot_config.gpio_cs = PIN_NUM_CS;
    slot_config.host_id = host.slot;

    // 挂载文件系统
    ret = esp_vfs_fat_sdspi_mount(mount_point, &host, &slot_config, &mount_config, &card);

    if (ret != ESP_OK) {
        if (ret == ESP_FAIL) {
            ESP_LOGE(TAG, "Failed to mount filesystem. "
                "If you want the card to be formatted, set the EXAMPLE_FORMAT_IF_MOUNT_FAILED menuconfig option.");
        } else {
            ESP_LOGE(TAG, "Failed to initialize the card (%s). "
                "Make sure SD card lines have pull-up resistors in place.", esp_err_to_name(ret));
        }
        return;
    }

    // Card has been initialized, print its properties
    sdmmc_card_print_info(stdout, card);

    // 使用POSIX和C标准库函数来处理文件
    // First create a file.
    ESP_LOGI(TAG, "Opening file");
    FILE* f = fopen(MOUNT_POINT"/hello.txt", "w");
    if (f == NULL) {
        ESP_LOGE(TAG, "Failed to open file for writing");
        return;
    }
    fprintf(f, "Hello %s!\n", card->cid.name);
    fclose(f);
    ESP_LOGI(TAG, "File written");

    // 重命名前检查目标文件是否存在
    struct stat st;
    if (stat(MOUNT_POINT"/foo.txt", &st) == 0) {
        // 删除(如果存在)
        unlink(MOUNT_POINT"/foo.txt");
    }

    // 重命名文件
    ESP_LOGI(TAG, "Renaming file");
    if (rename(MOUNT_POINT"/hello.txt", MOUNT_POINT"/foo.txt") != 0) {
        ESP_LOGE(TAG, "Rename failed");
        return;
    }

    // 读取文件
    ESP_LOGI(TAG, "Reading file");
    f = fopen(MOUNT_POINT"/foo.txt", "r");    // 读取方式打开文件
    if (f == NULL) {
        ESP_LOGE(TAG, "Failed to open file for reading");
        return;
    }
    char line[64];
    fgets(line, sizeof(line), f);    // 读取一行数据
    fclose(f);                       // 关闭文件
    // 在字符串中查找换行
    char* pos = strchr(line, '\n'); 
    if (pos) {
        *pos = '\0';                 // 替换为结束符
    }
    ESP_LOGI(TAG, "Read from file: '%s'", line);

    // 卸载分区并禁用SDMMC或SPI外设
    esp_vfs_fat_sdcard_unmount(mount_point, card);
    ESP_LOGI(TAG, "Card unmounted");

    // 卸载总线
    spi_bus_free(host.slot);
}

查看打印:


• 由 Leung 写于 2021 年 8 月 16 日

• 参考:ESP32 开发笔记(三)源码示例 9_SPI_SDCard 使用SPI总线实现TF卡文件系统示例

### ESP32 SPI SD Card Communication Example Code and Tutorial For establishing communication between an ESP32 module and an SD card using the SPI interface, specific libraries and configurations are essential. The Arduino environment provides comprehensive support for this task through dedicated libraries such as `SPI` and `SD`. Below is a detailed explanation along with example code. #### Library Installation To facilitate interaction with the SD card via SPI on ESP32, ensure that both the `SPI.h` and `SD.h` libraries are included at the beginning of your sketch. These libraries provide functions necessary for initializing and managing data transfer over the SPI bus[^1]. ```cpp #include <SPI.h> #include <SD.h> // Define chip select pin connected to SD card's CS line const int chipSelect = 5; void setup() { Serial.begin(115200); // Initialize serial monitor output while (!Serial) {} // Initialize the SD card if (!SD.begin(chipSelect)) { Serial.println("Card initialization failed!"); return; } Serial.println("Card initialized."); // Print file system type uint8_t cardType = SD.cardType(); if(cardType == CARD_NONE){ Serial.println("No SD card attached"); return; } else{ Serial.print("SD 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"); } } } void loop() { // Nothing happens after initialization. } ``` This script initializes the connection by setting up the hardware components involved in the process. It checks whether the SD card has been successfully mounted and identifies its type before proceeding further. In addition to basic initialization, more advanced operations like reading from or writing files can also be implemented based on project requirements. For instance: ```cpp File myFile = SD.open("/test.txt", FILE_WRITE); if (myFile) { myFile.println("Testing SD card write operation."); myFile.close(); // Close the file once done } else { Serial.println("Error opening test.txt"); } ``` The above snippet demonstrates how one might perform simple read/write actions against text files stored within the SD card memory space. --related questions-- 1. What other microcontroller platforms besides ESP32 offer built-in support for interfacing with SD cards? 2. How does changing the frequency of the SPI clock affect performance when communicating with an SD card? 3. Can you explain what precautions should be taken during physical wiring connections between ESP32 and SD modules? 4. Are there any differences in handling FAT32 versus exFAT formatted SD cards on ESP32 systems?
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Leung_ManWah

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值