3. 文件系统和存储

存储模块支持 FAT 和 littlefs 格式的虚拟文件系统,由 Zephyr DiskAccess 或 FlashArea(闪存映射)API 支持,具体取决于主板支持的类型。

请参阅 操作系统文件系统挂载.

3.1. 磁盘访问

所述 zephyr.DiskAccess 类可用于存取存储设备,如SD卡。该类使用Zephyr 磁盘访问 API 并实现该 os.AbstractBlockDev 协议。

与 SD 卡控制器一起使用时,SD 卡必须在启动时存在且不能移除;它们将在启动时由文件系统自动检测和初始化。使用磁盘驱动程序接口和文件系统通过磁盘访问来访问 SD 卡(见下文)。

在 mimxrt1050_evk 板上使用 SD 卡的 FatFS 示例:

import os
from zephyr import DiskAccess
bdev = zephyr.DiskAccess('SDHC')        # create block device object using DiskAccess
os.VfsFat.mkfs(bdev)                    # create FAT filesystem object using the disk storage block
os.mount(bdev, '/sd')                   # mount the filesystem at the SD card subdirectory
with open('/sd/hello.txt','w') as f:    # open a new file in the directory
    f.write('Hello world')              # write to the file
print(open('/sd/hello.txt').read())     # print contents of the file

3.2. 闪光区

所述 zephyr.FlashArea 类可以被用来实现一个低级别的存储系统或定制的文件系统的配置。要在设备上存储持久数据,建议使用更高级别的文件系统 API(见下文)。

该类使用Zephyr Flash 地图 API 并实现os.AbstractBlockDev协议。

使用 reel_board 或 rv32m1_vega_ri5cy 板上的内部闪存的示例用法:

import os
from zephyr import FlashArea
bdev = FlashArea(FlashArea.STORAGE, 4096)   # create block device object using FlashArea
os.VfsLfs2.mkfs(bdev)                       # create Little filesystem object using the flash area block
os.mount(bdev, '/flash')                    # mount the filesystem at the flash storage subdirectory
with open('/flash/hello.txt','w') as f:     # open a new file in the directory
    f.write('Hello world')                  # write to the file
print(open('/flash/hello.txt').read())      # print contents of the file

对于诸如 frdm_k64f 之类的 MicroPython 应用程序溢出到默认闪存存储分区的板,通过替换FlashArea.STORAGE为整数值 4 来使用暂存分区。