ESP32-FAT文件系統使用磨損均衡存儲文件筆記


基於ESP-IDF4.1

 1 /* 
 2    FAT文件系統存儲文件,使用磨損均衡庫wear-leveling
 3 */
 4 
 5 #include <stdlib.h>
 6 #include <stdio.h>
 7 #include <string.h>
 8 #include "esp_vfs.h"
 9 #include "esp_vfs_fat.h"
10 #include "esp_system.h"
11 
12 static const char *TAG = "example";
13 
14 // 磨損均衡處理實例
15 static wl_handle_t s_wl_handle = WL_INVALID_HANDLE;
16 
17 // 分區掛在路徑
18 const char *base_path = "/spiflash";
19 
20 void app_main(void)
21 {
22     ESP_LOGI(TAG, "Mounting FAT filesystem");
23 
24     // 命名設備分區,定義base_path。如果是新分區並且沒有格式化過則允許格式化分區
25     const esp_vfs_fat_mount_config_t mount_config = {
26             .max_files = 4,
27             .format_if_mount_failed = true,
28             .allocation_unit_size = CONFIG_WL_SECTOR_SIZE
29     };
30     esp_err_t err = esp_vfs_fat_spiflash_mount(base_path, "storage", &mount_config, &s_wl_handle);
31     if (err != ESP_OK) {
32         ESP_LOGE(TAG, "Failed to mount FATFS (%s)", esp_err_to_name(err));
33         return;
34     }
35     ESP_LOGI(TAG, "Opening file");
36     FILE *f = fopen("/spiflash/hello.txt", "wb"); // 讀寫或建立一個二進制文件
37     if (f == NULL) {
38         ESP_LOGE(TAG, "Failed to open file for writing");
39         return;
40     }
41     fprintf(f, "written using ESP-IDF %s\n", esp_get_idf_version());
42     fclose(f);
43     ESP_LOGI(TAG, "File written");
44 
45     // 打開
46     ESP_LOGI(TAG, "Reading file");
47     f = fopen("/spiflash/hello.txt", "rb"); // 讀寫打開一個二進制文件
48     if (f == NULL) {
49         ESP_LOGE(TAG, "Failed to open file for reading");
50         return;
51     }
52     char line[128];
53     // 從指定的流 f 讀取一行,並把它存儲在 line 所指向的字符串內
54     fgets(line, sizeof(line), f);
55     fclose(f);
56     // 查找換行符
57     char *pos = strchr(line, '\n');
58     if (pos) {
59         *pos = '\0'; //放置一個空字符串
60     }
61     ESP_LOGI(TAG, "Read from file: '%s'", line);
62 
63     // 卸載FAT文件系統
64     ESP_LOGI(TAG, "Unmounting FAT filesystem");
65     ESP_ERROR_CHECK( esp_vfs_fat_spiflash_unmount(base_path, s_wl_handle));
66 
67     ESP_LOGI(TAG, "Done");
68 }

 

原文:https://gitee.com/EspressifSystems/esp-idf


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM