ESP32-platformio+Arduino-SPI接口SD卡使用

ESP32, MCU  ·  2025-05-16

在Arduino平台上使用Platformio来使用SD卡,这里使用MonkeyPi-ESP32开发板为例;

1. 建立工程
  • 在VSCode中打开Platformio主页后新建项目,然后选择ESP-Wrover-Kit开发板,开发框架选择Arduino;
  • 添加SD库

在Platformio配置文件ini中添加sdfat库,如下:

[env:esp-wrover-kit]
platform = espressif32
board = esp-wrover-kit
framework = arduino
    
lib_deps = adafruit/SdFat - Adafruit Fork@^2.2.54
2. SD 读写测试代码

在main.cpp 文件中添加如下代码:

/*
  SD card read/write

 This example shows how to read and write data to and from an SD card file
 The circuit:
 * SD card attached to SPI bus as follows:
 ** MOSI - pin 23
 ** MISO - pin 19
 ** CLK - pin 18

 created   Nov 2010
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe

 This example code is in the public domain.

 */

#include <SPI.h>
//#include <SD.h>
#include "SdFat.h"
SdFat SD;

#define SD_CS_PIN 21
#define SD_SPI_SPEED SD_SCK_MHZ(4)

File myFile;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

    // Read any extra Serial data.
  do {
    delay(10);
  } while (Serial.available() && Serial.read() >= 0);
  // F stores strings in flash to save RAM
  Serial.println("Type any character to start.");
  while (!Serial.available()) {
    yield();
  }

  Serial.print("Initializing SD card...");

  if (!SD.begin(SD_CS_PIN,SD_SPI_SPEED)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  // re-open the file for reading:
  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
      Serial.write(myFile.read());
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop() {
  // nothing happens after setup
}


3.测试
  • 按照如下引脚连接sd卡和开发板:
ESP32开发板SD卡模块
3.3 V3V3
GNDGND
18SCK
23MOSI
19MISO
21CS
  • sd卡需要为fat32格式;
  • 烧录代码后,打开串口,测试看到如下结果说明正确:

    image-20250516225136057.png

 ESP32SD
评论
MonkeyPi. All Rights Reserved.

ICP粤ICP备19095914号-2