fatfs使用小结
整体fatfs的移植还是比较方便的。我个人觉得,其实fatfs是不太适合放在mcu使用的nor_flash上面的,因为每次f_open,f_close等操作都会触发文件的写入,而nor_flash每次写都要擦除,即使是一些小的改动也会擦除整个sector。nor_flash的擦写次数在10-100万次,一般都是10万次,所以使用fatfs的寿命可能不会太长。以上是我对fatfs的移植总结~,有什么
一、说明
下载链接:https://elm-chan.org/fsw/ff/
到最下方点击红色方框下载
我这里下载的最新版本R0.16,也可以点击Previous Releases下载历史版本。
二、文件移植

下载完成之后,解压得到ff16文件夹,移植只需要source文件当中的.c和.h文件

在keil工程中添加fatfs文件夹,在魔术棒中包含h文件路径之后,准备工作就做好了。我这里增加了一个test.c的测试文件,等下的测试就在这里进行。

我这里的工程是stm32f767zit6,其中的nor_flash文件是驱动片上的旺宏的nor_flash:MX25Lxx,其余的nor_flash应该也差不多。
三、修改代码
需要修改两个文件:diskio.c和ffconf.h
前面的diskio.c主要是操作对nor_flash的操作访问,包括读写,擦除等等。
ffconf.h主要配置一些宏。
下面是diskio.c的修改部分。
/*-----------------------------------------------------------------------*/
/* Low level disk I/O module SKELETON for FatFs (C)ChaN, 2025 */
/*-----------------------------------------------------------------------*/
/* If a working storage control module is available, it should be */
/* attached to the FatFs via a glue function rather than modifying it. */
/* This is an example of glue functions to attach various exsisting */
/* storage control modules to the FatFs module with a defined API. */
/*-----------------------------------------------------------------------*/
#include "ff.h" /* Basic definitions of FatFs */
#include "diskio.h" /* Declarations FatFs MAI */
/* Example: Declarations of the platform and disk functions in the project */
#include "Config.h"
/* Example: Mapping of physical drive number for each drive */
#define DEV_FLASH 0 /* Map FTL to physical drive 0 */
#define DEV_MMC 1 /* Map MMC/SD card to physical drive 1 */
#define DEV_USB 2 /* Map USB MSD to physical drive 2 */
DWORD get_fattime(void)
{
return ((DWORD)(sys.year+20)<<25) /* -1980 */
|((DWORD)sys.mon<<21)
|((DWORD)sys.day<<16)
|((DWORD)sys.hour<<11)
|((DWORD)sys.min<<5)
|((DWORD)sys.sec<<1);
}
/*-----------------------------------------------------------------------*/
/* Get Drive Status */
/*-----------------------------------------------------------------------*/
DSTATUS disk_status (
BYTE pdrv /* Physical drive nmuber to identify the drive */
)
{
DSTATUS stat;
switch (pdrv) {
case DEV_FLASH :
stat = RES_OK;
return stat;
case DEV_MMC :
return stat;
case DEV_USB :
return stat;
}
return STA_NOINIT;
}
/*-----------------------------------------------------------------------*/
/* Inidialize a Drive */
/*-----------------------------------------------------------------------*/
DSTATUS disk_initialize (
BYTE pdrv /* Physical drive nmuber to identify the drive */
)
{
DSTATUS stat;
switch (pdrv) {
case DEV_FLASH :
stat = RES_OK;
return stat;
case DEV_MMC :
return stat;
case DEV_USB :
return stat;
}
return STA_NOINIT;
}
/*-----------------------------------------------------------------------*/
/* Read Sector(s) */
/*-----------------------------------------------------------------------*/
DRESULT disk_read (
BYTE pdrv, /* Physical drive nmuber to identify the drive */
BYTE *buff, /* Data buffer to store read data */
LBA_t sector, /* Start sector in LBA */
UINT count /* Number of sectors to read */
)
{
DRESULT res;
switch (pdrv) {
case DEV_FLASH :
nor_flash_rd(sector * NOR_FLASH_SECTOR_SIZE, (unsigned char*)buff, count*NOR_FLASH_SECTOR_SIZE);
res = RES_OK;
return res;
case DEV_MMC :
return res;
case DEV_USB :
return res;
}
return RES_PARERR;
}
/*-----------------------------------------------------------------------*/
/* Write Sector(s) */
/*-----------------------------------------------------------------------*/
#if FF_FS_READONLY == 0
DRESULT disk_write (
BYTE pdrv, /* Physical drive nmuber to identify the drive */
const BYTE *buff, /* Data to be written */
LBA_t sector, /* Start sector in LBA */
UINT count /* Number of sectors to write */
)
{
DRESULT res;
unsigned long cnt;
switch (pdrv) {
case DEV_FLASH :
// printf("write in ---- sector = %d, count = %d\r\n", sector, count);
for(cnt=0; cnt<count; cnt++)
{ nor_flash_sector_erase((sector + cnt) * NOR_FLASH_SECTOR_SIZE); }
nor_flash_wt(sector * NOR_FLASH_SECTOR_SIZE, (unsigned char*)buff, count*NOR_FLASH_SECTOR_SIZE);
res = RES_OK;
return res;
case DEV_MMC :
return res;
case DEV_USB :
return res;
}
return RES_PARERR;
}
#endif
/*-----------------------------------------------------------------------*/
/* Miscellaneous Functions */
/*-----------------------------------------------------------------------*/
DRESULT disk_ioctl (
BYTE pdrv, /* Physical drive nmuber (0..) */
BYTE cmd, /* Control code */
void *buff /* Buffer to send/receive control data */
)
{
DRESULT res = RES_OK;
LBA_t *var_buff, sec_start, sec_end;
switch (pdrv) {
case DEV_FLASH :
switch(cmd)
{
/* nor_falsh 驱动层完成了write busy */
case CTRL_SYNC:
break;
/* 所有的扇区数量 */
case GET_SECTOR_COUNT:
*(LBA_t*)buff = 512; // NOR_FLASH_MAX_SIZE/NOR_FLASH_SECTOR_SIZE;
break;
/* 扇区大小 */
case GET_SECTOR_SIZE:
*(WORD*)buff = NOR_FLASH_SECTOR_SIZE;
break;
/* deepseek:
f_mkfs 算法会参考这个值 以及其他参数如磁盘总大小
计算出最佳的扇区每簇 _SS 数量 并确保簇的起始扇区与块边界对齐 */
case GET_BLOCK_SIZE:
*(DWORD*)buff = NOR_FLASH_BLOCK_SIZE / NOR_FLASH_SECTOR_SIZE;
break;
/* start sector, sector count */
case CTRL_TRIM:
var_buff = (LBA_t*)buff;
sec_start = var_buff[0];
sec_end = var_buff[1];
for(LBA_t cnt=sec_start; cnt<=sec_end; cnt++)
{ nor_flash_sector_erase(cnt * NOR_FLASH_SECTOR_SIZE); }
break;
default:
break;
}
return res;
case DEV_MMC :
return res;
case DEV_USB :
return res;
}
return RES_PARERR;
}
disk_status直接返回ok,原因是驱动底层已经做了写等待的操作。
其中disk_write函数,在写入的时候,会先擦除。这是因为fatfs不关心底层驱动,也不做磨损均衡,默认该设备就是可以正常读写的。
disk_ioctl添加了CTRL_SYNC、GET_SECTOR_COUNT、GET_SECTOR_SIZE、GET_BLOCK_SIZE、CTRL_TRIM等宏参数。
CTRL_SYNC:用于同步,这里不用写,也是因为驱动底层已经做了写等待的操作。
GET_SECTOR_COUNT:用于获取扇区数量,我这里测试写的512,实际上我这块nor_flash的扇区数量很多,在格式化文件系统的时候会擦除等待很长时间(这块flash一个扇区的擦除时间最大在400ms),这里测试就写小一点。
GET_SECTOR_SIZE:系统可以计算出磁盘的总大小。
CTRL_TRIM:这个参数其实可以不用写,因为每次disk_write我们都会擦除扇区。这里是当顶层调用f_unlink等函数的时候,擦除该存储位置。
接下来是ffconf.h文件的宏定义修改:
/*---------------------------------------------------------------------------/
/ Configurations of FatFs Module
/---------------------------------------------------------------------------*/
#include "nor_flash.h"
#define FFCONF_DEF 80386 /* Revision ID */
/*---------------------------------------------------------------------------/
/ Function Configurations
/---------------------------------------------------------------------------*/
#define FF_FS_READONLY 0
/* This option switches read-only configuration. (0:Read/Write or 1:Read-only)
/ Read-only configuration removes writing API functions, f_write(), f_sync(),
/ f_unlink(), f_mkdir(), f_chmod(), f_rename(), f_truncate(), f_getfree()
/ and optional writing functions as well. */
#define FF_FS_MINIMIZE 0
/* This option defines minimization level to remove some basic API functions.
/
/ 0: Basic functions are fully enabled.
/ 1: f_stat(), f_getfree(), f_unlink(), f_mkdir(), f_truncate() and f_rename()
/ are removed.
/ 2: f_opendir(), f_readdir() and f_closedir() are removed in addition to 1.
/ 3: f_lseek() function is removed in addition to 2. */
#define FF_USE_FIND 0
/* This option switches filtered directory read functions, f_findfirst() and
/ f_findnext(). (0:Disable, 1:Enable 2:Enable with matching altname[] too) */
#define FF_USE_MKFS 1
/* This option switches f_mkfs(). (0:Disable or 1:Enable) */
#define FF_USE_FASTSEEK 0
/* This option switches fast seek feature. (0:Disable or 1:Enable) */
#define FF_USE_EXPAND 0
/* This option switches f_expand(). (0:Disable or 1:Enable) */
#define FF_USE_CHMOD 0
/* This option switches attribute control API functions, f_chmod() and f_utime().
/ (0:Disable or 1:Enable) Also FF_FS_READONLY needs to be 0 to enable this option. */
#define FF_USE_LABEL 0
/* This option switches volume label API functions, f_getlabel() and f_setlabel().
/ (0:Disable or 1:Enable) */
#define FF_USE_FORWARD 0
/* This option switches f_forward(). (0:Disable or 1:Enable) */
#define FF_USE_STRFUNC 1
#define FF_PRINT_LLI 0
#define FF_PRINT_FLOAT 0
#define FF_STRF_ENCODE 0
/* FF_USE_STRFUNC switches string API functions, f_gets(), f_putc(), f_puts() and
/ f_printf().
/
/ 0: Disable. FF_PRINT_LLI, FF_PRINT_FLOAT and FF_STRF_ENCODE have no effect.
/ 1: Enable without LF-CRLF conversion.
/ 2: Enable with LF-CRLF conversion.
/
/ FF_PRINT_LLI = 1 makes f_printf() support long long argument and FF_PRINT_FLOAT = 1/2
/ makes f_printf() support floating point argument. These features want C99 or later.
/ When FF_LFN_UNICODE >= 1 with LFN enabled, string API functions convert the character
/ encoding in it. FF_STRF_ENCODE selects assumption of character encoding ON THE FILE
/ to be read/written via those functions.
/
/ 0: ANSI/OEM in current CP
/ 1: Unicode in UTF-16LE
/ 2: Unicode in UTF-16BE
/ 3: Unicode in UTF-8
*/
/*---------------------------------------------------------------------------/
/ Locale and Namespace Configurations
/---------------------------------------------------------------------------*/
#define FF_CODE_PAGE 437
/* This option specifies the OEM code page to be used on the target system.
/ Incorrect code page setting can cause a file open failure.
/
/ 437 - U.S.
/ 720 - Arabic
/ 737 - Greek
/ 771 - KBL
/ 775 - Baltic
/ 850 - Latin 1
/ 852 - Latin 2
/ 855 - Cyrillic
/ 857 - Turkish
/ 860 - Portuguese
/ 861 - Icelandic
/ 862 - Hebrew
/ 863 - Canadian French
/ 864 - Arabic
/ 865 - Nordic
/ 866 - Russian
/ 869 - Greek 2
/ 932 - Japanese (DBCS)
/ 936 - Simplified Chinese (DBCS)
/ 949 - Korean (DBCS)
/ 950 - Traditional Chinese (DBCS)
/ 0 - Include all code pages above and configured by f_setcp()
*/
#define FF_USE_LFN 1
#define FF_MAX_LFN 255
/* The FF_USE_LFN switches the support for LFN (long file name).
/
/ 0: Disable LFN. FF_MAX_LFN has no effect.
/ 1: Enable LFN with static working buffer on the BSS. Always NOT thread-safe.
/ 2: Enable LFN with dynamic working buffer on the STACK.
/ 3: Enable LFN with dynamic working buffer on the HEAP.
/
/ To enable the LFN, ffunicode.c needs to be added to the project. The LFN feature
/ requiers certain internal working buffer occupies (FF_MAX_LFN + 1) * 2 bytes and
/ additional (FF_MAX_LFN + 44) / 15 * 32 bytes when exFAT is enabled.
/ The FF_MAX_LFN defines size of the working buffer in UTF-16 code unit and it can
/ be in range of 12 to 255. It is recommended to be set 255 to fully support the LFN
/ specification.
/ When use stack for the working buffer, take care on stack overflow. When use heap
/ memory for the working buffer, memory management functions, ff_memalloc() and
/ ff_memfree() exemplified in ffsystem.c, need to be added to the project. */
#define FF_LFN_UNICODE 2
/* This option switches the character encoding on the API when LFN is enabled.
/
/ 0: ANSI/OEM in current CP (TCHAR = char)
/ 1: Unicode in UTF-16 (TCHAR = WCHAR)
/ 2: Unicode in UTF-8 (TCHAR = char)
/ 3: Unicode in UTF-32 (TCHAR = DWORD)
/
/ Also behavior of string I/O functions will be affected by this option.
/ When LFN is not enabled, this option has no effect. */
#define FF_LFN_BUF 255
#define FF_SFN_BUF 12
/* This set of options defines size of file name members in the FILINFO structure
/ which is used to read out directory items. These values should be suffcient for
/ the file names to read. The maximum possible length of the read file name depends
/ on character encoding. When LFN is not enabled, these options have no effect. */
#define FF_FS_RPATH 0
/* This option configures support for relative path feature.
/
/ 0: Disable relative path and remove related API functions.
/ 1: Enable relative path and dot names. f_chdir() and f_chdrive() are available.
/ 2: f_getcwd() is available in addition to 1.
*/
#define FF_PATH_DEPTH 10
/* This option defines maximum depth of directory in the exFAT volume. It is NOT
/ relevant to FAT/FAT32 volume.
/ For example, FF_PATH_DEPTH = 3 will able to follow a path "/dir1/dir2/dir3/file"
/ but a sub-directory in the dir3 will not able to be followed and set current
/ directory.
/ The size of filesystem object (FATFS) increases FF_PATH_DEPTH * 24 bytes.
/ When FF_FS_EXFAT == 0 or FF_FS_RPATH == 0, this option has no effect.
*/
/*---------------------------------------------------------------------------/
/ Drive/Volume Configurations
/---------------------------------------------------------------------------*/
#define FF_VOLUMES 1
/* Number of volumes (logical drives) to be used. (1-10) */
#define FF_STR_VOLUME_ID 0
#define FF_VOLUME_STRS "RAM","NAND","CF","SD","SD2","USB","USB2","USB3"
/* FF_STR_VOLUME_ID switches support for volume ID in arbitrary strings.
/ When FF_STR_VOLUME_ID is set to 1 or 2, arbitrary strings can be used as drive
/ number in the path name. FF_VOLUME_STRS defines the volume ID strings for each
/ logical drive. Number of items must not be less than FF_VOLUMES. Valid
/ characters for the volume ID strings are A-Z, a-z and 0-9, however, they are
/ compared in case-insensitive. If FF_STR_VOLUME_ID >= 1 and FF_VOLUME_STRS is
/ not defined, a user defined volume string table is needed as:
/
/ const char* VolumeStr[FF_VOLUMES] = {"ram","flash","sd","usb",...
*/
#define FF_MULTI_PARTITION 0
/* This option switches support for multiple volumes on the physical drive.
/ By default (0), each logical drive number is bound to the same physical drive
/ number and only an FAT volume found on the physical drive will be mounted.
/ When this feature is enabled (1), each logical drive number can be bound to
/ arbitrary physical drive and partition listed in the VolToPart[]. Also f_fdisk()
/ will be available. */
#define FF_MIN_SS NOR_FLASH_SECTOR_SIZE
#define FF_MAX_SS NOR_FLASH_SECTOR_SIZE
/* This set of options configures the range of sector size to be supported. (512,
/ 1024, 2048 or 4096) Always set both 512 for most systems, generic memory card and
/ harddisk, but a larger value may be required for on-board flash memory and some
/ type of optical media. When FF_MAX_SS is larger than FF_MIN_SS, FatFs is
/ configured for variable sector size mode and disk_ioctl() needs to implement
/ GET_SECTOR_SIZE command. */
#define FF_LBA64 0
/* This option switches support for 64-bit LBA. (0:Disable or 1:Enable)
/ To enable the 64-bit LBA, also exFAT needs to be enabled. (FF_FS_EXFAT == 1) */
#define FF_MIN_GPT 0x10000000
/* Minimum number of sectors to switch GPT as partitioning format in f_mkfs() and
/ f_fdisk(). 2^32 sectors maximum. This option has no effect when FF_LBA64 == 0. */
#define FF_USE_TRIM 1
/* This option switches support for ATA-TRIM. (0:Disable or 1:Enable)
/ To enable this feature, also CTRL_TRIM command should be implemented to
/ the disk_ioctl(). */
/*---------------------------------------------------------------------------/
/ System Configurations
/---------------------------------------------------------------------------*/
#define FF_FS_TINY 1
/* This option switches tiny buffer configuration. (0:Normal or 1:Tiny)
/ At the tiny configuration, size of file object (FIL) is reduced FF_MAX_SS bytes.
/ Instead of private sector buffer eliminated from the file object, common sector
/ buffer in the filesystem object (FATFS) is used for the file data transfer. */
#define FF_FS_EXFAT 0
/* This option switches support for exFAT filesystem. (0:Disable or 1:Enable)
/ To enable exFAT, also LFN needs to be enabled. (FF_USE_LFN >= 1)
/ Note that enabling exFAT discards ANSI C (C89) compatibility. */
#define FF_FS_NORTC 0
#define FF_NORTC_MON 1
#define FF_NORTC_MDAY 1
#define FF_NORTC_YEAR 2025
/* The option FF_FS_NORTC switches timestamp feature. If the system does not have
/ an RTC or valid timestamp is not needed, set FF_FS_NORTC = 1 to disable the
/ timestamp feature. Every object modified by FatFs will have a fixed timestamp
/ defined by FF_NORTC_MON, FF_NORTC_MDAY and FF_NORTC_YEAR in local time.
/ To enable timestamp function (FF_FS_NORTC = 0), get_fattime() need to be added
/ to the project to read current time form real-time clock. FF_NORTC_MON,
/ FF_NORTC_MDAY and FF_NORTC_YEAR have no effect.
/ These options have no effect in read-only configuration (FF_FS_READONLY = 1). */
#define FF_FS_CRTIME 0
/* This option enables(1)/disables(0) the timestamp of the file created. When
/ set 1, the file created time is available in FILINFO structure. */
#define FF_FS_NOFSINFO 0
/* If you need to know the correct free space on the FAT32 volume, set bit 0 of
/ this option, and f_getfree() on the first time after volume mount will force
/ a full FAT scan. Bit 1 controls the use of last allocated cluster number.
/
/ bit0=0: Use free cluster count in the FSINFO if available.
/ bit0=1: Do not trust free cluster count in the FSINFO.
/ bit1=0: Use last allocated cluster number in the FSINFO if available.
/ bit1=1: Do not trust last allocated cluster number in the FSINFO.
*/
#define FF_FS_LOCK 0
/* The option FF_FS_LOCK switches file lock function to control duplicated file open
/ and illegal operation to open objects. This option must be 0 when FF_FS_READONLY
/ is 1.
/
/ 0: Disable file lock function. To avoid volume corruption, application program
/ should avoid illegal open, remove and rename to the open objects.
/ >0: Enable file lock function. The value defines how many files/sub-directories
/ can be opened simultaneously under file lock control. Note that the file
/ lock control is independent of re-entrancy. */
#define FF_FS_REENTRANT 0
#define FF_FS_TIMEOUT 1000
/* The option FF_FS_REENTRANT switches the re-entrancy (thread safe) of the FatFs
/ module itself. Note that regardless of this option, file access to different
/ volume is always re-entrant and volume control functions, f_mount(), f_mkfs()
/ and f_fdisk(), are always not re-entrant. Only file/directory access to
/ the same volume is under control of this featuer.
/
/ 0: Disable re-entrancy. FF_FS_TIMEOUT have no effect.
/ 1: Enable re-entrancy. Also user provided synchronization handlers,
/ ff_mutex_create(), ff_mutex_delete(), ff_mutex_take() and ff_mutex_give(),
/ must be added to the project. Samples are available in ffsystem.c.
/
/ The FF_FS_TIMEOUT defines timeout period in unit of O/S time tick.
*/
/*--- End of configuration options ---*/
主要修改:
FF_FS_TINY:使用 Tiny 模式,节省 RAM
FF_USE_MKFS:设置为 1,使能格式化功能,首次使用 Flash 时需要。
USE_TRIM:启用 disk_ioctl中的 USE_TRIM命令,FATFS 通过它来通知底层哪些扇区可以擦除。这里其实可以不用的。原因就是每次写入实际都做了擦除的。
FF_VOLUMES:卷数量,我这里只有一个就设置1
FF_MIN_SS,FF_MAX_SS:扇区大小,如果只有一个存储器,都设置一样。有多个存储器,按照最小的和最大的来设置。
FF_USE_STRFUNC:用于打印会输出时间,这里写1之后需要定义get_fattime函数,我放在diskio.c中的。
FF_CODE_PAGE:437 使用us,中文库太大了。
FF_USE_LFN:文件名,占用的内存放在哪里。
FF_LFN_UNICODE:2,使用ytf-8编码。
四、运行测试
到这里我们就可以开始编译测试了,这里是测试代码:
#include "Config.h"
#include "ff.h"
#include <stdlib.h>
static timeCtrl nor_flash_dly;
static SemaphoreHandle_t nor_flash_mutex;
static unsigned char nor_flash_spi_send(unsigned char data)
{ return spi_send(SPI5, data); }
static void nor_flash_cs(unsigned char status)
{ IO_SET(GPIOF, 6, CMP_VALUE(status, 0, 0, 1)); }
static void nor_flash_dly_us(unsigned short us)
{ dly_us(&nor_flash_dly, us); }
static void nor_flash_lock(unsigned char cmd)
{
if(cmd)
{ xSemaphoreTake(nor_flash_mutex, portMAX_DELAY); }
else { xSemaphoreGive(nor_flash_mutex); }
}
static char* ret_order_index_to_char(unsigned int index)
{
static char buff[20];
memset(buff, 0 ,20);
snprintf((char*)buff, 20, "wt_index = %d", index);
return buff;
}
struct _data
{
unsigned long index;
unsigned long data_len;
unsigned char data[2048];
unsigned char desc[32];
};
/* fatfs */
FATFS fs; /* 文件系统对象 */
MKFS_PARM opt;
FIL fp_obj; /* 文件对象 */
char *write_data = "hello fatfs!";
unsigned int write_bytes, read_bytes;
char work_buff[FF_MAX_SS];
unsigned char key_wt, key_rd, key_delete;
unsigned int wt_no, rd_no;
unsigned int wt_index, rd_index, delete_index;
unsigned char wt_err, rd_err;
struct _data wt_data, rd_data;
#define PATH ""
void fatfs_test(void *para)
{
FRESULT ret;
nor_flash_mutex = xSemaphoreCreateMutex();
nor_flash_init(nor_flash_spi_send, nor_flash_cs, nor_flash_dly_us, nor_flash_lock);
/* 立即挂载 */
ret = f_mount(&fs, PATH, 1);
if(ret == FR_NO_FILESYSTEM)
{
PRINTF("no filesystem found. formatting...\n");
opt.fmt = FM_FAT; /* 文件系统类型 */
opt.n_fat = 0; /* 0表示默认值 */
opt.align = 0;
opt.n_root = 0;
opt.au_size = FF_MAX_SS; /* 簇大小 */
/* 格式化 这会触发全片擦除和FAT结构写入 */
ret = f_mkfs(PATH, &opt, work_buff, FF_MAX_SS);
if(ret == FR_OK)
{
PRINTF("f_mount again\n");
/* 重新挂载 */
ret = f_mount(&fs, PATH, 1);
if(ret == FR_OK) { PRINTF("filesystem success\n"); }
else { PRINTF("filesystem fail again\n"); }
}
else
{
PRINTF("format error: %d\n", ret);
}
}
else if(ret != FR_OK)
{
PRINTF("mount error: %d\n", ret);
}
for(;;)
{
u1_process();
if(key_wt == 1)
{
key_wt = 0;
wt_err = 0;
wt_index = wt_no;
memset(&wt_data, 0, sizeof(struct _data));
wt_data.index = wt_index;
memcpy(wt_data.data, write_data, strlen(write_data));
wt_data.data_len = strlen(write_data);
snprintf((char*)wt_data.desc, 20, "wt cnt = %d", wt_index);
ret = FR_OK;
ret = f_open(&fp_obj, ret_order_index_to_char(wt_index), FA_WRITE | FA_CREATE_ALWAYS);
if(!ret) { PRINTF("write open file success!\n"); }
else { PRINTF("write open file failure! code = %d\n", ret); wt_err = 1; }
ret = FR_OK;
ret = f_write(&fp_obj, (char*)&wt_data, sizeof(struct _data), &write_bytes);
if(!ret) { PRINTF("write success, write_bytes=%d\n", write_bytes); }
else { PRINTF("write failure! code = %d\n", ret); wt_err = 1; }
ret = FR_OK;
ret = f_close(&fp_obj);
if(!ret) PRINTF("write close success!\n");
else { PRINTF("write close failure! code = %d\n", ret); wt_err = 1; }
if(!wt_err)
{
PRINTF("wt_data.index :%d\n", (int)wt_data.index);
PRINTF("wt_data.data :%s\n", wt_data.data);
PRINTF("wt_data.data_len :%d\n", (int)wt_data.data_len);
PRINTF("wt_data.desc :%s\n", wt_data.desc);
}
}
if(key_rd == 1)
{
key_rd = 0;
rd_err = 0;
memset(&rd_data, 0, sizeof(struct _data));
rd_index = rd_no;
ret = FR_OK;
ret = f_open(&fp_obj, ret_order_index_to_char(rd_index), FA_OPEN_EXISTING | FA_READ);
if(!ret) { PRINTF("read open file success!\n"); }
else { PRINTF("read open file failure! code = %d\n", ret); rd_err = 1; }
ret = FR_OK;
ret = f_read(&fp_obj, (char*)&rd_data, sizeof(struct _data), &read_bytes);
if(!ret)
{
PRINTF("read success, read_bytes=%d\n", read_bytes);
PRINTF("rd_data.index :%d\n", (int)rd_data.index);
PRINTF("rd_data.data :%s\n", rd_data.data);
PRINTF("rd_data.data_len :%d\n", (int)rd_data.data_len);
PRINTF("rd_data.desc :%s\n", rd_data.desc);
}
else { PRINTF("read failure! code = %d\n", ret); rd_err = 1; }
ret = FR_OK;
ret = f_close(&fp_obj);
if(!ret) { PRINTF("read close success!\n"); }
else { PRINTF("read close failure! code = %d\n", ret); rd_err = 1; }
}
if(key_delete == 1)
{
key_delete = 0;
ret = FR_OK;
ret = f_unlink(ret_order_index_to_char(delete_index));
if(!ret) { PRINTF("File deleted successfully.\n");}
else { PRINTF("Error deleting file! code = %d\n", ret); }
}
vTaskDelay(1000);
}
}
我这里的测试逻辑是使用串口,输入指令来控制读写和删除:

前面的nor_flash_init初始化,包含了对spi的读写注册,片选,一个us延时用于最大的超时等待计时,可以传入osDelay也可以,互斥锁等参数。
注册nor_flash驱动之后我们挂载文件系统。
ret = f_mount(&fs, PATH, 1);
没有文件系统会调用f_mkfs()初始化。之后的重启就不会调用f_mkfs了。
测试结果:
写入:输入01 01,读取:02 01,擦除:03 01,再次读取:02 01
(01 02 03分别是串口设置的写入,读取,擦除,后面跟着的是文件编号)

到这里就测试结束了。
五、总结
整体fatfs的移植还是比较方便的。我个人觉得,其实fatfs是不太适合放在mcu使用的nor_flash上面的,因为每次f_open,f_close等操作都会触发文件的写入,而nor_flash每次写都要擦除,即使是一些小的改动也会擦除整个sector。nor_flash的擦写次数在10-100万次,一般都是10万次,所以使用fatfs的寿命可能不会太长。
以上是我对fatfs的移植总结~,有什么写错的地方希望看到的读者能指出来,大家共同进步~
下次总结一下littlefs文件系统的移植。
更多推荐



所有评论(0)