我正在尝试使用连接到 SD 卡作为 SDMMC 主机的 ESP32 来格式化 SD 卡。我想知道如何在 Arduino 框架内将其格式化为 FAT32。有谁知道这是否可以在 Arduino 框架内完成?我可以创建、读取、写入和删除文件,但我不知道如何格式化 SD 卡。
我相信使用 Espressif 的 ESPIDF 是可能的,但我不知道如何在 Arduino 中使其工作。下页介绍了使用连接为 SDMMC 主机的 SD 卡的基础知识:
这不包括如何格式化以此方式连接的 SD 卡。我希望我能提供更多细节,但我不知道从哪里开始。感谢任何和所有的帮助。
有人建议这可能在 espidf 中有效:
#include "esp_vfs_fat.h"
#include "driver/sdmmc_host.h"
#include "sdmmc_cmd.h"
#include "SD.h"
void setup() {
Serial.begin(115200);
// Initialize SDMMC host driver
sdmmc_host_t host = SDMMC_HOST_DEFAULT();
sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
esp_vfs_fat_sdmmc_mount_config_t mount_config = {
.format_if_mount_failed = true,
.max_files = 5,
.allocation_unit_size = 16 * 1024
};
sdmmc_card_t* card;
esp_err_t err = esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, &card);
if (err != ESP_OK) {
Serial.printf("Failed to mount SD card (%s)\n", esp_err_to_name(err));
return;
}
Serial.println("SD card mounted successfully");
// List files in root directory
File root = SD.open("/");
File file = root.openNextFile();
while (file) {
Serial.println(file.name());
file = root.openNextFile();
}
}
void loop() {
}
我创建了一个片段来在 Arduino 或 ESP-IDF 上格式化 SD 卡。
链接:https://gist.github.com/dizcza/a35d8c1d09450369ed2f08f6803b5101
源代码:
#include "ff.h"
#include "vfs_fat_internal.h"
/**
* Usage:
*
* Arduino:
* SD.begin();
* format_sdcard();
*
* ESP-IDF:
* See https://github.com/espressif/esp-idf/blob/b63ec47238fd6aa6eaa59f7ad3942cbdff5fcc1f/examples/storage/sd_card/sdmmc/main/sd_card_example_main.c#L75
* esp_vfs_fat_sdmmc_mount(mount_point, &host, &slot_config, &mount_config, &card);
* format_sdcard();
*
* Then proceed without remounting.
*/
esp_err_t format_sdcard() {
char drv[3] = {'0', ':', 0};
const size_t workbuf_size = 4096;
void* workbuf = NULL;
esp_err_t err = ESP_OK;
ESP_LOGW("sdcard", "Formatting the SD card");
size_t allocation_unit_size = 16 * 1024;
int sector_size_default = 512;
workbuf = ff_memalloc(workbuf_size);
if (workbuf == NULL) {
return ESP_ERR_NO_MEM;
}
size_t alloc_unit_size = esp_vfs_fat_get_allocation_unit_size(
sector_size_default,
allocation_unit_size);
#if (ESP_IDF_VERSION_MAJOR < 5)
FRESULT res = f_mkfs(drv, FM_ANY, alloc_unit_size, workbuf, workbuf_size);
#else
const MKFS_PARM opt = {(BYTE)FM_ANY, 0, 0, 0, alloc_unit_size};
FRESULT res = f_mkfs(drv, &opt, workbuf, workbuf_size);
#endif /* ESP_IDF_VERSION_MAJOR */
if (res != FR_OK) {
err = ESP_FAIL;
ESP_LOGE("sdcard", "f_mkfs failed (%d)", res);
}
free(workbuf);
ESP_LOGI("sdcard", "Successfully formatted the SD card");
return err;
}