#ifndef SD_HPP #define SD_HPP #include #include #include #include "esp_vfs_fat.h" #include "sdmmc_cmd.h" #include "driver/sdmmc_host.h" static const char *SD_TAG = "sd_driver"; #define MOUNT_POINT "/sdcard" const char mount_point[] = MOUNT_POINT; sdmmc_card_t *card; #define SD_PIN_CLK GPIO_NUM_48 #define SD_PIN_CMD GPIO_NUM_45 #define SD_PIN_D0 GPIO_NUM_47 #define SD_PIN_D1 GPIO_NUM_21 #define SD_PIN_D2 GPIO_NUM_39 #define SD_PIN_D3 GPIO_NUM_38 void init_sd() { 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 = false, .max_files = 5, .allocation_unit_size = 16 * 1024, .disk_status_check_enable = false, }; ESP_LOGI(SD_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(SD_TAG, "Using SDMMC peripheral"); sdmmc_host_t host = SDMMC_HOST_DEFAULT(); // This initializes the slot without card detect (CD) and write protect (WP) signals. // Modify slot_config.gpio_cd and slot_config.gpio_wp if your board has these signals. sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); // Set bus width to use: slot_config.width = 4; // On chips where the GPIOs used for SD card can be configured, set them in // the slot_config structure: slot_config.clk = SD_PIN_CLK; slot_config.cmd = SD_PIN_CMD; slot_config.d0 = SD_PIN_D0; slot_config.d1 = SD_PIN_D1; slot_config.d2 = SD_PIN_D2; slot_config.d3 = SD_PIN_D3; // Enable internal pullups on enabled pins. The internal pullups // are insufficient however, please make sure 10k external pullups are // connected on the bus. This is for debug / example purpose only. slot_config.flags |= SDMMC_SLOT_FLAG_INTERNAL_PULLUP; ESP_LOGI(SD_TAG, "Mounting filesystem"); ret = esp_vfs_fat_sdmmc_mount(mount_point, &host, &slot_config, &mount_config, &card); if (ret != ESP_OK) { if (ret == ESP_FAIL) { ESP_LOGE(SD_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(SD_TAG, "Failed to initialize the card (%s). " "Make sure SD card lines have pull-up resistors in place.", esp_err_to_name(ret)); } return; } ESP_LOGI(SD_TAG, "Filesystem mounted"); // Card has been initialized, print its properties sdmmc_card_print_info(stdout, card); } void deinit_sd() { esp_vfs_fat_sdcard_unmount(mount_point, card); ESP_LOGI(SD_TAG, "Card unmounted"); } #endif /* SD_HPP */