• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 开发指导<a name="ZH-CN_TOPIC_0000001152860497"></a>
2
3-   [示例代码](#section1034515054620)
4
5移植LittleFS到新硬件设备上,需要申明lfs\_config:
6
7```
8const struct lfs_config cfg = {
9    // block device operations
10    .read  = user_provided_block_device_read,
11    .prog  = user_provided_block_device_prog,
12    .erase = user_provided_block_device_erase,
13    .sync  = user_provided_block_device_sync,
14
15    // block device configuration
16    .read_size = 16,
17    .prog_size = 16,
18    .block_size = 4096,
19    .block_count = 128,
20    .cache_size = 16,
21    .lookahead_size = 16,
22    .block_cycles = 500,
23};
24```
25
26其中.read,.prog,.erase,.sync分别对应该硬件平台上的底层的读写\\擦除\\同步等接口。
27
28read\_size 每次读取的字节数,可以比物理读单元大以改善性能,这个数值决定了读缓存的大小,但值太大会带来更多的内存消耗。
29
30prog\_size 每次写入的字节数,可以比物理写单元大以改善性能,这个数值决定了写缓存的大小,必须是read\_size的整数倍,但值太大会带来更多的内存消耗。
31
32block\_size 每个擦除块的字节数,可以比物理擦除单元大,但此数值应尽可能小因为每个文件至少会占用一个块。必须是prog\_size的整数倍。
33
34block\_count 可以被擦除的块数量,这取决于块设备的容量及擦除块的大小。
35
36## 示例代码<a name="section1034515054620"></a>
37
38代码实现如下:
39
40```
41#include "lfs.h"
42#include "stdio.h"
43
44lfs_t lfs;
45lfs_file_t file;
46
47const struct lfs_config cfg = {
48    // block device operations
49    .read  = user_provided_block_device_read,
50    .prog  = user_provided_block_device_prog,
51    .erase = user_provided_block_device_erase,
52    .sync  = user_provided_block_device_sync,
53
54    // block device configuration
55    .read_size = 16,
56    .prog_size = 16,
57    .block_size = 4096,
58    .block_count = 128,
59    .cache_size = 16,
60    .lookahead_size = 16,
61    .block_cycles = 500,
62};
63
64int main(void) {
65    // mount the filesystem
66    int err = lfs_mount(&lfs, &cfg);
67
68    // reformat if we can't mount the filesystem
69    // this should only happen on the first boot
70    if (err) {
71        lfs_format(&lfs, &cfg);
72        lfs_mount(&lfs, &cfg);
73    }
74
75    // read current count
76    uint32_t boot_count = 0;
77    lfs_file_open(&lfs, &file, "boot_count", LFS_O_RDWR | LFS_O_CREAT);
78    lfs_file_read(&lfs, &file, &boot_count, sizeof(boot_count));
79
80    // update boot count
81    boot_count += 1;
82    lfs_file_rewind(&lfs, &file);
83    lfs_file_write(&lfs, &file, &boot_count, sizeof(boot_count));
84
85    // remember the storage is not updated until the file is closed successfully
86    lfs_file_close(&lfs, &file);
87
88    // release any resources we were using
89    lfs_unmount(&lfs);
90
91    // print the boot count
92    printf("boot_count: %d\n", boot_count);
93}
94```
95
96