ARM单片机FATFS文件系统的移植
ARM单片机FATFS文件系统的移植
- 测试效果
- 前提条件
- 下载所需源码
- FATFS 文件系统
- SFUD万能驱动
- 加入工程
- 接口驱动
- 测试代码
- FreeRTOS10.0.1
- FATFS FF14A
- SFUD V1.1.0
- STM32F103ZET6
FATFS在STM32上特别是由CubeMX工具移植变得简单,相对在其他芯片平台没有这个工具时,清晰的了解移植的方法步骤变得更加重要了。
测试效果
前提条件
FATFS移植需要做的:
- 配置FATFS,裁剪相关功能
- 完善使用操作系统时的互斥锁接口
- 完善内存管理接口
- 完善diskio.c中对存储设备的操作接口
本工程,使用W25Q16BV
spi flash芯片,所以移植SFUD完善对FLASH的操作接口
本工程源码
下载所需源码
FATFS 文件系统
下载地址,可能需代理工具
SFUD万能驱动
官方移植方法参考
本博客移植参考
加入工程
port目录下皆是需要修改的的文件
,diskio.c
需配合disk_port.c
做出微调,其他无需修改
接口驱动
diskio.c
调整如下:
包含驱动接口头文件disk_port.h
调用disk_drv_array
里的相关函数
/*-----------------------------------------------------------------------*/
/* Low level disk I/O module SKELETON for FatFs (C)ChaN, 2019 */
/*-----------------------------------------------------------------------*/
/* 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" /* Obtains integer types */
#include "diskio.h" /* Declarations of disk functions */
#include "disk_port.h"
/*-----------------------------------------------------------------------*/
/* Get Drive Status */
/*-----------------------------------------------------------------------*/DSTATUS disk_status (BYTE pdrv /* Physical drive nmuber to identify the drive */
)
{return disk_drv_array[pdrv].get_disk_status_port();
}/*-----------------------------------------------------------------------*/
/* Inidialize a Drive */
/*-----------------------------------------------------------------------*/DSTATUS disk_initialize (BYTE pdrv /* Physical drive nmuber to identify the drive */
)
{return disk_drv_array[pdrv].disk_init_port();
}/*-----------------------------------------------------------------------*/
/* 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 */
)
{return disk_drv_array[pdrv].disk_read_port(buff, sector, count);
}/*-----------------------------------------------------------------------*/
/* Write Sector(s) */
/*-----------------------------------------------------------------------*/#if FF_FS_READONLY == 0DRESULT 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 */
)
{return disk_drv_array[pdrv].disk_write_port(buff, sector, count);
}#endif/*-----------------------------------------------------------------------*/
/* Miscellaneous Functions */
/*-----------------------------------------------------------------------*/DRESULT disk_ioctl (BYTE pdrv, /* Physical drive nmuber (0..) */BYTE cmd, /* Control code */void *buff /* Buffer to send/receive control data */
)
{return disk_drv_array[pdrv].disk_ioctl_port(cmd, buff);
}
disk_port.c
磁盘驱动接口
/*** @file disk_port.c** @date 2021-01-05** @author aron566** @copyright None.** @brief 磁盘接口驱动映射** @details None.** @version V1.0*/
#ifdef __cplusplus ///<use C compiler
extern "C" {#endif
/** Includes -----------------------------------------------------------------*/
/* Private includes ----------------------------------------------------------*/
#include "disk_port.h"
#include "rtc_opt.h"
/** Privated typedef ----------------------------------------------------------*//** Private macros -----------------------------------------------------------*//** Private constants --------------------------------------------------------*//** Private variables --------------------------------------------------------*//** Private function prototypes ----------------------------------------------*//** Private user code --------------------------------------------------------*/
/*** @defgroup SPI FLASH DRIVE FUNC* @{*/
static DSTATUS spi_flash_disk_status(void);
static DSTATUS spi_flash_disk_initialize(void);
static DRESULT spi_flash_disk_read(BYTE *buff, LBA_t sector, UINT count);
static DRESULT spi_flash_disk_write(const BYTE *buff, LBA_t sector, UINT count);
static DRESULT spi_flash_disk_ioctl(BYTE cmd, void *buff);
/** @}*/
/** Public variables ---------------------------------------------------------*/
DISK_DRV_FUNC_MAP_Typedef_t disk_drv_array[DEV_TYPE_MAX] =
{[DEV_SPI_FLASH] = {.get_disk_status_port = spi_flash_disk_status,.disk_init_port = spi_flash_disk_initialize,.disk_read_port = spi_flash_disk_read,.disk_write_port = spi_flash_disk_write,.disk_ioctl_port = spi_flash_disk_ioctl},
};osMutexDef_t disk_mutex_array[DEV_TYPE_MAX] = {0};
/** Private application code -------------------------------------------------*/
/*******************************************************************************
*
* Static code
*
********************************************************************************
*//********************************************************************* @brief spi磁盘状态读取* @param [in]None* @return 1 Drive not initialized 2 No medium in the drive 4 Write protected* @author aron566* @version V1.0* @date 2020-01-04*******************************************************************/
static DSTATUS spi_flash_disk_status(void)
{sfud_flash *flash = sfud_get_device(SFUD_W25Q16BV_DEVICE_INDEX);if(flash == NULL){return STA_NOINIT;}uint8_t status;sfud_read_status(flash, &status);return (DSTATUS)status;
}/********************************************************************* @brief spi磁盘初始化* @param [in]None* @return 0 OK 1 Drive not initialized 2 No medium in the drive 4 Write protected* @author aron566* @version V1.0* @date 2020-01-04*******************************************************************/
static DSTATUS spi_flash_disk_initialize(void)
{sfud_flash *flash = sfud_get_device(SFUD_W25Q16BV_DEVICE_INDEX);if(flash == NULL){return STA_NOINIT;}sfud_err result = sfud_device_init(flash);if(result != SFUD_SUCCESS){return STA_NOINIT;}return 0;
}/********************************************************************* @brief spi磁盘读取指定扇区数的数据到缓冲区* @param [out]buff 缓冲区* @param [in]sector 起始扇区号* @param [in]count 扇区数* @return 0: Successful 1: R/W Error 2: Write Protected 3: Not Ready 4: Invalid Parameter* @author aron566* @version V1.0* @date 2020-01-04*******************************************************************/
static DRESULT spi_flash_disk_read(BYTE *buff, LBA_t sector, UINT count)
{sfud_flash *flash = sfud_get_device(SFUD_W25Q16BV_DEVICE_INDEX);if(flash == NULL){return RES_PARERR;}sfud_err result = sfud_read(flash, sector*512, 512*count, (uint8_t *)buff);if(result != SFUD_SUCCESS){return RES_ERROR;}return RES_OK;
}/********************************************************************* @brief spi磁盘写入数据到指定扇区数* @param [in]buff* @param [in]sector* @param [in]count* @return 0: Successful 1: R/W Error 2: Write Protected 3: Not Ready 4: Invalid Parameter* @author aron566* @version V1.0* @date 2020-01-04*******************************************************************/
static DRESULT spi_flash_disk_write(const BYTE *buff, LBA_t sector, UINT count)
{sfud_flash *flash = sfud_get_device(SFUD_W25Q16BV_DEVICE_INDEX);if(flash == NULL){return RES_PARERR;}sfud_err result = sfud_erase_write(flash, sector*512, 512*count, (const uint8_t *)buff);if(result != SFUD_SUCCESS){return RES_ERROR;}return RES_OK;
}/********************************************************************* @brief spi磁盘特殊操作* @param [in]cmd* @param [in]buff* @return 0: Successful 1: R/W Error 2: Write Protected 3: Not Ready 4: Invalid Parameter* @author aron566* @version V1.0* @date 2020-01-04*******************************************************************/
static DRESULT spi_flash_disk_ioctl(BYTE cmd, void *buff)
{//#define CTRL_SYNC 0 /* Complete pending write process (needed at FF_FS_READONLY == 0) */
//#define GET_SECTOR_COUNT 1 /* Get media size (needed at FF_USE_MKFS == 1) */
//#define GET_SECTOR_SIZE 2 /* Get sector size (needed at FF_MAX_SS != FF_MIN_SS) */
//#define GET_BLOCK_SIZE 3 /* Get erase block size (needed at FF_USE_MKFS == 1) */
//#define CTRL_TRIM 4 /* Inform device that the data on the block of sectors is no longer used (needed at FF_USE_TRIM == 1) */switch(cmd){case CTRL_SYNC:return RES_OK;case GET_SECTOR_COUNT:*(DWORD*)buff = 4096;/**< PAGE SIZE:256,SECTOR SIZE:4KB,BLOCK SIZE:32/64KB,W25Q16BV TOTOAL SIZE:512*4KB*/return RES_OK;case GET_SECTOR_SIZE:*(DWORD*)buff = FF_MAX_SS;/**< if use 512Byte then erase size is 2 PAGE SIZE, if use 4KB then erase size is 1 SECTOR SIZE.*/return RES_OK;case GET_BLOCK_SIZE:*(DWORD*)buff = 1;/**< 擦除扇区的最小个数(1*512Byte = 2 PAGE SIZE),per 32K/64K block size to erase*/return RES_OK;case CTRL_TRIM:return RES_PARERR;/**< 通知扇区数据不使用--未开启功能*/default:break;}return RES_PARERR;
}/** Public application code --------------------------------------------------*/
/*******************************************************************************
*
* Public code
*
********************************************************************************
*/
/********************************************************************* @brief 获取当前时间秒数* @param [in]None* @return s* @author aron566* @version V1.0* @date 2020-01-04*******************************************************************/
DWORD disk_get_rtc_time_s(void)
{return RTC_Current_Time_S();
}#ifdef __cplusplus ///<end extern c
}
#endif
/******************************** End of file *********************************/
disk_port.h
磁盘驱动接口
/*** @file disk_port.h** @date 2021-01-04** @author aron566** @brief 磁盘接口驱动* * @version V1.0*/
#ifndef DISK_PORT_H
#define DISK_PORT_H
#ifdef __cplusplus ///<use C compiler
extern "C" {#endif
/** Includes -----------------------------------------------------------------*/
#include <stdint.h> /**< nedd definition of uint8_t */
#include <stddef.h> /**< need definition of NULL */
#include <stdbool.h>/**< need definition of BOOL */
#include <stdio.h> /**< if need printf */
#include <stdlib.h>
#include <string.h>
#include <limits.h> /**< need variable max value */
/** Private includes ---------------------------------------------------------*/
#include "main.h"
#include "ff.h"
#include "diskio.h"
/** Private defines ----------------------------------------------------------*//** Exported typedefines -----------------------------------------------------*/
/*磁盘状态读取*/
typedef DSTATUS(*pdisk_status_func)(void);
/*磁盘初始化*/
typedef DSTATUS(*pdisk_initialize_func)(void);
/*磁盘读取数据*/
typedef DRESULT(*pdisk_read_func)(BYTE *buff, /* Data buffer to store read data */LBA_t sector, /* Start sector in LBA */UINT count /* Number of sectors to read */
);
/*磁盘写入数据*/
typedef DRESULT (*pdisk_write_func)(const BYTE *buff, /* Data to be written */LBA_t sector, /* Start sector in LBA */UINT count /* Number of sectors to write */
);
/*磁盘控制*/
typedef DRESULT (*pdisk_ioctl_func)(BYTE cmd, /* Control code */void *buff /* Buffer to send/receive control data */
);typedef struct disk_drv
{pdisk_status_func get_disk_status_port;pdisk_initialize_func disk_init_port;pdisk_read_func disk_read_port;pdisk_write_func disk_write_port;pdisk_ioctl_func disk_ioctl_port;
}DISK_DRV_FUNC_MAP_Typedef_t;
/** Exported constants -------------------------------------------------------*//** Exported macros-----------------------------------------------------------*/
/* Definitions of physical drive number for each drive */
#define DEV_RAM 0 /* Example: Map Ramdisk to physical drive 0 */
#define DEV_MMC 1 /* Example: Map MMC/SD card to physical drive 1 */
#define DEV_USB 2 /* Example: Map USB MSD to physical drive 2 */
#define DEV_SPI_FLASH 3
#define DEV_TYPE_MAX DEV_SPI_FLASH+1
/** Exported variables -------------------------------------------------------*/
extern DISK_DRV_FUNC_MAP_Typedef_t disk_drv_array[DEV_TYPE_MAX];/**< 磁盘设备驱动接口*/extern osMutexDef_t disk_mutex_array[DEV_TYPE_MAX];/**< 磁盘同步锁*/
/** Exported functions prototypes --------------------------------------------*/
DWORD disk_get_rtc_time_s(void);
#ifdef __cplusplus ///<end extern c
}
#endif
#endif
/******************************** End of file *********************************/
ffsystem.c
FATFS的信号量动态内存管理
/*------------------------------------------------------------------------*/
/* Sample Code of OS Dependent Functions for FatFs */
/* (C)ChaN, 2018 */
/*------------------------------------------------------------------------*/#include "ff.h"
#include "disk_port.h"#if FF_USE_LFN == 3 /* Dynamic memory allocation *//*------------------------------------------------------------------------*/
/* Allocate a memory block */
/*------------------------------------------------------------------------*/void* ff_memalloc ( /* Returns pointer to the allocated memory block (null if not enough core) */UINT msize /* Number of bytes to allocate */
)
{return pvPortMalloc(msize); /* Allocate a new memory block with POSIX API */
}/*------------------------------------------------------------------------*/
/* Free a memory block */
/*------------------------------------------------------------------------*/void ff_memfree (void* mblock /* Pointer to the memory block to free (nothing to do if null) */
)
{vPortFree(mblock); /* Free the memory block with POSIX API */
}#endif#if FF_FS_REENTRANT /* Mutal exclusion *//*------------------------------------------------------------------------*/
/* Create a Synchronization Object */
/*------------------------------------------------------------------------*/
/* This function is called in f_mount() function to create a new
/ synchronization object for the volume, such as semaphore and mutex.
/ When a 0 is returned, the f_mount() function fails with FR_INT_ERR.
*///const osMutexDef_t Mutex[FF_VOLUMES]; /* Table of CMSIS-RTOS mutex */int ff_cre_syncobj ( /* 1:Function succeeded, 0:Could not create the sync object */BYTE vol, /* Corresponding volume (logical drive number) */FF_SYNC_t* sobj /* Pointer to return the created sync object */
)
{/* Win32 */
// *sobj = CreateMutex(NULL, FALSE, NULL);
// return (int)(*sobj != INVALID_HANDLE_VALUE);/* uITRON */
// T_CSEM csem = {TA_TPRI,1,1};
// *sobj = acre_sem(&csem);
// return (int)(*sobj > 0);/* uC/OS-II */
// OS_ERR err;
// *sobj = OSMutexCreate(0, &err);
// return (int)(err == OS_NO_ERR);/* FreeRTOS */
// *sobj = xSemaphoreCreateMutex();
// return (int)(*sobj != NULL);/* CMSIS-RTOS */*sobj = osMutexNew(&disk_mutex_array[vol]);return (int)(*sobj != NULL);
}/*------------------------------------------------------------------------*/
/* Delete a Synchronization Object */
/*------------------------------------------------------------------------*/
/* This function is called in f_mount() function to delete a synchronization
/ object that created with ff_cre_syncobj() function. When a 0 is returned,
/ the f_mount() function fails with FR_INT_ERR.
*/int ff_del_syncobj ( /* 1:Function succeeded, 0:Could not delete due to an error */FF_SYNC_t sobj /* Sync object tied to the logical drive to be deleted */
)
{/* Win32 */
// return (int)CloseHandle(sobj);/* uITRON */
// return (int)(del_sem(sobj) == E_OK);/* uC/OS-II */
// OS_ERR err;
// OSMutexDel(sobj, OS_DEL_ALWAYS, &err);
// return (int)(err == OS_NO_ERR);/* FreeRTOS */
// vSemaphoreDelete(sobj);
// return 1;/* CMSIS-RTOS */return (int)(osMutexDelete(sobj) == osOK);
}/*------------------------------------------------------------------------*/
/* Request Grant to Access the Volume */
/*------------------------------------------------------------------------*/
/* This function is called on entering file functions to lock the volume.
/ When a 0 is returned, the file function fails with FR_TIMEOUT.
*/int ff_req_grant ( /* 1:Got a grant to access the volume, 0:Could not get a grant */FF_SYNC_t sobj /* Sync object to wait */
)
{/* Win32 */
// return (int)(WaitForSingleObject(sobj, FF_FS_TIMEOUT) == WAIT_OBJECT_0);/* uITRON */
// return (int)(wai_sem(sobj) == E_OK);/* uC/OS-II */
// OS_ERR err;
// OSMutexPend(sobj, FF_FS_TIMEOUT, &err));
// return (int)(err == OS_NO_ERR);/* FreeRTOS */
// return (int)(xSemaphoreTake(sobj, FF_FS_TIMEOUT) == pdTRUE);/* CMSIS-RTOS */return (int)(osMutexWait(sobj, FF_FS_TIMEOUT) == osOK);
}/*------------------------------------------------------------------------*/
/* Release Grant to Access the Volume */
/*------------------------------------------------------------------------*/
/* This function is called on leaving file functions to unlock the volume.
*/void ff_rel_grant (FF_SYNC_t sobj /* Sync object to be signaled */
)
{/* Win32 */
// ReleaseMutex(sobj);/* uITRON */
// sig_sem(sobj);/* uC/OS-II */
// OSMutexPost(sobj);/* FreeRTOS */
// xSemaphoreGive(sobj);/* CMSIS-RTOS */osMutexRelease(sobj);
}#endif#if !FF_FS_READONLY && !FF_FS_NORTC
/********************************************************************* @brief 获取当前时间秒数* @param [in]None* @return s* @author aron566* @version V1.0* @date 2020-01-04*******************************************************************/
DWORD get_fattime (void)
{return disk_get_rtc_time_s();
}
#endif
ffconf.h
FATFS配置文件
/*---------------------------------------------------------------------------/
/ FatFs Functional Configurations
/---------------------------------------------------------------------------*/
#ifndef FF_CONFIG_H
#define FF_CONFIG_H#define FFCONF_DEF 80196 /* 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_STRFUNC 2
/* This option switches string functions, f_gets(), f_putc(), f_puts() and f_printf().
/
/ 0: Disable string functions.
/ 1: Enable without LF-CRLF conversion.
/ 2: Enable with LF-CRLF conversion. */#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() function. (0:Disable or 1:Enable) */#define FF_USE_FASTSEEK 1
/* This option switches fast seek function. (0:Disable or 1:Enable) */#define FF_USE_EXPAND 0
/* This option switches f_expand function. (0:Disable or 1:Enable) */#define FF_USE_CHMOD 1
/* This option switches attribute manipulation 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 functions, f_getlabel() and f_setlabel().
/ (0:Disable or 1:Enable) */#define FF_USE_FORWARD 0
/* This option switches f_forward() function. (0:Disable or 1:Enable) *//*---------------------------------------------------------------------------/
/ Locale and Namespace Configurations
/---------------------------------------------------------------------------*/#define FF_CODE_PAGE 936
/* 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 3
#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 function
/ 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 it 255 to fully support 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 128
#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_STRF_ENCODE 3
/* When FF_LFN_UNICODE >= 1 with LFN enabled, string I/O functions, f_gets(),
/ f_putc(), f_puts and f_printf() convert the character encoding in it.
/ This option 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
*/#define FF_FS_RPATH 2
/* This option configures support for relative path.
/
/ 0: Disable relative path and remove related functions.
/ 1: Enable relative path. f_chdir() and f_chdrive() are available.
/ 2: f_getcwd() function is available in addition to 1.
*//*---------------------------------------------------------------------------/
/ Drive/Volume Configurations
/---------------------------------------------------------------------------*/#define FF_VOLUMES 10/**< 逻辑驱动号就是挂载的设备号0:,也对应设备驱动号DEV_SPI_FLASH*/
/* 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 drives. 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 needs to be defined 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 function is enabled (1), each logical drive number can be bound to
/ arbitrary physical drive and partition listed in the VolToPart[]. Also f_fdisk()
/ funciton will be available. */#define FF_MIN_SS 512
#define FF_MAX_SS 512
/* 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() function 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 function. 0x100000000 max. This option has no effect when FF_LBA64 == 0. */#define FF_USE_TRIM 0
/* This option switches support for ATA-TRIM. (0:Disable or 1:Enable)
/ To enable Trim function, also CTRL_TRIM command should be implemented to the
/ disk_ioctl() function. *//*---------------------------------------------------------------------------/
/ System Configurations
/---------------------------------------------------------------------------*/#define FF_FS_TINY 0
/* This option switches tiny buffer configuration. (0:Normal or 1:Tiny)
/ At the tiny configuration, size of file object (FIL) is shrinked 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 2020
/* The option FF_FS_NORTC switches timestamp functiton. If the system does not have
/ any RTC function or valid timestamp is not needed, set FF_FS_NORTC = 1 to disable
/ the timestamp function. 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() function 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_NOFSINFO 0
/* If you need to know correct free space on the FAT32 volume, set bit 0 of this
/ option, and f_getfree() function at 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. */#include "cmsis_os.h" // O/S definitions
#define FF_FS_REENTRANT 1
#define FF_FS_TIMEOUT 1000
#define FF_SYNC_t osMutexId
/* 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() function, are always not re-entrant. Only file/directory access
/ to the same volume is under control of this function.
/
/ 0: Disable re-entrancy. FF_FS_TIMEOUT and FF_SYNC_t have no effect.
/ 1: Enable re-entrancy. Also user provided synchronization handlers,
/ ff_req_grant(), ff_rel_grant(), ff_del_syncobj() and ff_cre_syncobj()
/ function, must be added to the project. Samples are available in
/ option/syscall.c.
/
/ The FF_FS_TIMEOUT defines timeout period in unit of time tick.
/ The FF_SYNC_t defines O/S dependent sync object type. e.g. HANDLE, ID, OS_EVENT*,
/ SemaphoreHandle_t and etc. A header file for O/S definitions needs to be
/ included somewhere in the scope of ff.h. */#endif
/*--- End of configuration options ---*/
测试代码
/*** @file fatfs_opt.c** @date 2021-01-05** @author aron566** @copyright None.** @brief 文件系统操作** @details 1、** @version V1.0*/
#ifdef __cplusplus ///<use C compiler
extern "C" {#endif
/** Includes -----------------------------------------------------------------*/
/* Private includes ----------------------------------------------------------*/
#include "fatfs_opt.h"
#include "ff.h"
/** Private typedef ----------------------------------------------------------*//** Private macros -----------------------------------------------------------*//** Private constants --------------------------------------------------------*/
/** Public variables ---------------------------------------------------------*/
/** Private variables --------------------------------------------------------*/
static BYTE work[FF_MAX_SS];/**< 挂载工作内存,不可放入线程,占用内存太大*/
static FATFS fsobject;/**< 磁盘挂载对象,不可放入线程,占用内存太大*/
static FIL fp;/**< 文件对象,不可放入线程,占用内存太大*/
/** Private function prototypes ----------------------------------------------*//** Private user code --------------------------------------------------------*//** Private application code -------------------------------------------------*/
/*******************************************************************************
*
* Static code
*
********************************************************************************
*//** Public application code --------------------------------------------------*/
/*******************************************************************************
*
* Public code
*
********************************************************************************
*/
/********************************************************************* @brief 测试fatfs* @param [in]None* @return None* @author aron566* @version V1.0* @date 2020-01-05*******************************************************************/
void fs_test(void)
{// MKFS_PARM parm;
// parm.fmt = FM_FAT32;
// parm.n_fat = 0;/*逻辑驱动器号*/
// parm.align = 512; /*分配扇区大小*/
// parm.n_root = 0;
// parm.au_size = 0;
// printf("fatfs test start.\n");
// /* 格式化文件系统 */
// res = f_mkfs("3:", &parm, work, sizeof(work));//"3:"是卷标,来自于 #define SPI_FLASH 0
// if (res)
// {// printf("format faild.\n");
// return ;
// }
// else
// {// printf("format ok.\n");
// }/*挂载*/FRESULT res;res = f_mount(&fsobject, "3:", 1); /**< 挂载文件系统, "3:"就是挂载的设备号为3的设备,1立即执行挂载*/if(res == FR_NO_FILESYSTEM) /**< FR_NO_FILESYSTEM值为13,表示没有有效的设备*/{printf("res = %d\r\n", res);res = f_mkfs("3:", 0, work, sizeof(work));printf("f_mkfs is over\r\n");printf("res = %d\r\n", res);res = f_mount(NULL, "3:", 1);/**< 取消文件系统*/res = f_mount(&fsobject, "3:", 1);/**< 挂载文件系统*/}printf("res = %d\r\n", res);/*创建文件*/res = f_open(&fp, "3:/test.txt", FA_CREATE_NEW|FA_WRITE|FA_READ);if(res){printf("open file faild.\r\n");if(res == FR_EXIST){printf("the file is existed.\r\n");f_open(&fp, "3:/test.txt", FA_WRITE|FA_READ);}}else{printf("open file ok.\r\n");}/* write a message */UINT write_size;res = f_write(&fp, "Hello,World!", 12, &write_size);//printf("res write:%d\r\n",res);if (write_size == 12){printf("write ok!\r\n");}else{printf("write faild!\r\n");}FSIZE_t fsize;fsize = f_size(&fp);printf("file size:%d Bytes.\r\n",fsize);BYTE buf[50];memset(buf, 0, 50);f_lseek(&fp, 0);UINT read_size;res = f_read(&fp, buf, 12, &read_size);if (res == FR_OK){printf("read file ok!\r\n");printf("read size:%d Bytes.\r\n",read_size);}else{printf("read file faild!\r\n");}printf("read data:\r\n");for(int index = 0;index < 12;index++){printf("0x%02X ",buf[index]);}printf("\n%s\n", buf);/*关闭文件*/f_close(&fp);
}#include "sfud.h"
/*** SFUD demo for the first flash device test.** @param addr flash start address* @param size test flash size* @param size test flash data buffer*/
void sfud_demo(uint32_t addr, size_t size, uint8_t *data)
{sfud_err result = SFUD_SUCCESS;extern sfud_flash *sfud_dev;const sfud_flash *flash = sfud_get_device(SFUD_W25Q16BV_DEVICE_INDEX);size_t i;/* prepare write data */for (i = 0; i < size; i++){data[i] = i;}/* erase test */result = sfud_erase(flash, addr, size);if (result == SFUD_SUCCESS){printf("Erase the %s flash data finish. Start from 0x%08X, size is %zu.\r\n", flash->name, addr, size);}else{printf("Erase the %s flash data failed.\r\n", flash->name);return;}/* write test */result = sfud_write(flash, addr, size, data);if (result == SFUD_SUCCESS){printf("Write the %s flash data finish. Start from 0x%08X, size is %zu.\r\n", flash->name, addr, size);}else{printf("Write the %s flash data failed.\r\n", flash->name);return;}/* read test */result = sfud_read(flash, addr, size, data);if (result == SFUD_SUCCESS){printf("Read the %s flash data success. Start from 0x%08X, size is %zu. The data is:\r\n", flash->name, addr, size);printf("Offset (h) 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\r\n");for (i = 0; i < size; i++){if (i % 16 == 0){printf("[%08X] ", addr + i);}printf("%02X ", data[i]);if (((i + 1) % 16 == 0) || i == size - 1){printf("\r\n");}}printf("\r\n");}else{printf("Read the %s flash data failed.\r\n", flash->name);}/* data check */for (i = 0; i < size; i++){if (data[i] != i % 256){printf("Read and check write data has an error. Write the %s flash data failed.\r\n", flash->name);break;}}if (i == size){printf("The %s flash test is success.\r\n", flash->name);}
}#ifdef __cplusplus ///<end extern c
}
#endif
/******************************** End of file *********************************/
ARM单片机FATFS文件系统的移植相关推荐
- FatFs文件系统的移植
FatFs 的底层可以写一次命令,读写多个扇区.FatFs的设计的读写的思想就很好,小块的数据,我就经过Buffer来存储,大块的数据,我就直接进行存取,那样速度,效率高了很多,看图: FatFs文件 ...
- STM32+雷龙SD NAND(贴片SD卡)完成FATFS文件系统移植与测试
一.前言 在STM32项目开发中,经常会用到存储芯片存储数据. 比如:关机时保存机器运行过程中的状态数据,上电再从存储芯片里读取数据恢复:在存储芯片里也会存放很多资源文件.比如,开机音乐,界面上的菜单 ...
- 【FatFs】基于STM32 SD卡移植FatFs文件系统
相关文章 <[SDIO]SDIO.SD卡.FatFs文件系统相关文章索引> 1.前言 FatFs是一个通用的FAT/exFAT文件系统模块,用于小型嵌入式系统.它完全是由 ANSI C 语 ...
- FatFs文件系统移植过程及中度分析
FatFs 是一个通用的文件系统(FAT/exFAT)模块,用于在小型嵌入式系统中实现FAT文件系统. FatFs 组件的编写遵循ANSI C(C89),完全分离于磁盘 I/O 层,因此不依赖于硬件平 ...
- 基于STM32采用CS创世 SD NAND(贴片SD卡)完成FATFS文件系统移植与测试
一.前言 在STM32项目开发中,经常会用到存储芯片存储数据. 比如:关机时保存机器运行过程中的状态数据,上电再从存储芯片里读取数据恢复:在存储芯片里也会存放很多资源文件.比如,开机音乐,界面上的菜单 ...
- 模拟SPI进行TF卡操作+Fatfs文件系统移植
FATFS版本:FATFS R0.13b SD卡容量:16G 概述 本文的重点是进行Fatfs文件系统的移植和初步的使用.TF卡的操作实际上是指令操作,即你想它发送固定的CMD指令,它接收到指令给你返 ...
- STM32CubeMX学习笔记(25)——FatFs文件系统使用(操作SPI Flash)
一.FatFs简介 FatFs 是面向小型嵌入式系统的一种通用的 FAT 文件系统.它完全是由 ANSI C 语言编写并且完全独立于底层的 I/O 介质.因此它可以很容易地不加修改地移植到其他的处理器 ...
- STM32CubeMX学习笔记(27)——FatFs文件系统使用(操作SD卡)
一.FatFs简介 FatFs 是面向小型嵌入式系统的一种通用的 FAT 文件系统.它完全是由 ANSI C 语言编写并且完全独立于底层的 I/O 介质.因此它可以很容易地不加修改地移植到其他的处理器 ...
- FatFs文件系统笔记--R0.13c
目录 1. FatFs文件系统简介 1.1 FatFs的目录结构 1.2 FatFs帮助文档 1.3 FatFs源码 2. FatFs 文件系统的移植 2.1 FatFs 分层体系 2.1 Fa ...
最新文章
- 结构光|一文详解相移步长的选择问题
- iOS Hacker 动态库 dylib 注入
- .NET 6 数组拷贝性能对比
- python核心编程第三版_《Python核心编程(第3版)》
- 无比乐java游戏_传智播客Java JavaEE+物联网云计算 就业班
- Ubuntu 用户提权到Root
- android 多线程编程
- 【对话系统】对话系统核心技术概要
- 服务器mstsc远程桌面,远程桌面工具,详细教您如何使用远程桌面工具mstsc连接远程桌面...
- html中嵌入flvplayer.swf播放器,播放视频
- 1人30天44587行代码,分享舍得网开发经验【修订版】
- 如何用计算机制作思维导向图,mindmaster使用方法,手把手教你制作思维导图
- LODOP直接用base64码输出图片
- web大作业介绍自己的家乡_中国10大乡村名鸭!快来看看自己家乡的鸭子是否上榜...
- 华为与泰国TSE将全面合作建设亚太区智能光伏
- Simulink仿真入门到精通(十七) Simulink代码生成技术详解
- win10动态壁纸无法通过右击属性的个性化来换掉
- JavaEE-多线程(基础篇一)
- 华为人才在线加入HCIA班级
- 模拟量采集软件虚拟精度提升方案