ESP-IDF tutorial for ESP32 (15) – Use internal Flash to store files

Main textFrom the original column “ESP32 Teaching Column (Based on ESP-IDF)”, explain how to use ESP-IDF to build ESP32 programs, publish articles andWe will continue to add new content to published articles! Every article has been carefully polished!

↓↓↓Enter the column directory page through the dialog box below↓↓↓
Request to enter directory_ O x

Whether to enter ESP32 teachingnavigation(based on ESP-IDF)?

       Sure


We learned about partition tables and virtual file systems (VFS) earlier, and we will use them in this article

1. Wear Leveling API

Most of the flash used by ESP32, especially SPI flash, has a sector structure, and each sector only allows a limited number of erase/modify operations. In order to avoid overuse of a certain sector, Espressif provides a wear leveling component that can help users balance the wear between sectors without user intervention.

1. Two important functions

Function nameesp_vfs_fat_spiflash_mount()
function prototypeesp_err_t esp_vfs_fat_spiflash_mount(const char *base_path, const char *partition_label, constesp_vfs_fat_mount_config_t *mount_config, wl_handle_t *wl_handle)
meaningInitialize the Fat file system in SPI flash, initialize the wear leveling component, and register it to VFS through the given mount point.
return valueesp_err_t
parameterbase_path: Type isconst char *;Name the complete mount, such as:/data
partition_label: Type isconst char *;Partition label to be mounted
mount_config: Type isesp_vfs_fat_mount_config_t *; Pass the mounting configuration through the structure
wl_handle: Type iswl_handle_t *; Output a wear leveling component handle here
Function nameesp_vfs_fat_spiflash_unmount()
function prototypeesp_err_tesp_vfs_fat_spiflash_unmount(const char *base_path, wl_handle_twl_handle)
meaningUnmount the Fat file system and unmount it from the VFS, while turning off the corresponding wear leveling components
return valueesp_err_t
parameterbase_path: Type isconst char *;Name the mount to be uninstalled
wl_handleThe type iswl_handle_t;Wear leveling component handle obtained when mounting

2. Related configuration structures

For the structure mentioned above

typedef struct {
	// If the FAT partition fails to be mounted and this member is true, create a partition table and format the file system.
    bool format_if_mount_failed;

	//The maximum number of files that can be opened in the mounted file system
    int max_files;
    
    // If format_if_mount_failed is set and the mount fails, format the card using the given allocation unit size.
    // Must be a power of 2, between the sector size and 128*(sector size).
    // For SD cards, the sector size is always 512 bytes.
    // For wear leveling components, the sector size is determined by the CONFIG_WL_SECTOR_SIZE option.
	// ==========================
	// Using a larger allocation unit size will result in higher read/write performance and higher overhead when storing small files.
	// Setting this field to 0 will cause the allocation unit to be set to the sector size.
    size_t allocation_unit_size;
} esp_vfs_fat_mount_config_t;

1. Mount the internal flash as a Fat file system

Function example

//Global variables, required when unmounting the file system
static wl_handle_t wlHandle = WL_INVALID_HANDLE;

void mount_flash_partition(void){
    const esp_vfs_fat_mount_config_t mount_config = {
        .max_files = 4,
        .format_if_mount_failed = true,
        .allocation_unit_size = CONFIG_WL_SECTOR_SIZE
    };
    esp_err_t err = esp_vfs_fat_spiflash_mount("/data", "storage", &mount_config, &wlHandle);
    if (err != ESP_OK) {
        ESP_LOGE(TAG, "Failed to mount FatFS, error name: %s", esp_err_to_name(err));
        return;
    }
    ESP_LOGI(TAG, "Mounted successfully");
}

2. Use the standard C library to read and write files

void app_main() {
	//Call the function written above to mount the partition
    mount_flash_partition();

    //Open the "/data/test.txt" file and write "Hello World"
    FILE *fp = fopen("/data/test.txt", "w");
    if (fp == NULL) {
        ESP_LOGE(TAG, "Failed to open /data/test.txt");
        return;
    }
    fprintf(fp, "Hello World\n");
    fclose(fp);

    //Open the "/data/test.txt" file again and read the content
    fp = fopen("/data/test.txt", "r");
    if (fp == NULL) {
        ESP_LOGE(TAG, "Failed to open /data/test.txt");
        return;
    }
    char line[64];
    while (fgets(line, sizeof(line), fp) != NULL) {
        printf("%s", line);
    }
    fclose(fp);

	//Unmount the file system, this function is defined below
    unmount_flash_partition();
}

3. Uninstall the file system

void unmount_flash_partition(void) {
    esp_err_t err = esp_vfs_fat_spiflash_unmount("/data", wlHandle);
    if (err != ESP_OK) {
        ESP_LOGE(TAG, "Uninstallation failed, error: %s", esp_err_to_name(err));
        return;
    }
    ESP_LOGI(TAG, "Uninstall successful");
}

Related Posts

Introduction to Bluetooth (6): Bluetooth Low Energy Information Interaction

What is a host computer

[Data structure] Huffman tree and Huffman coding implementation (C language)

Timing analysis and constraints based on Xlinx (1)—-What is timing analysis? What are timing constraints? What is timing closure?

Hongmeng OS2.0 device development Hi3861-basic function summary

npm install reports error command C:\WINDOWS\system32\cmd.exe /d /s /c node-gyp rebuild

How to use the esp8266 module (detailed explanation) essential for getting started

[Set Sail] OpenHarmony Expedition 01

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*