ARM單片機(jī)FATFS文件系統(tǒng)的移植

@toc

  • FreeRTOS10.0.1
  • FATFS FF14A
  • SFUD V1.1.0
  • STM32F103ZET6

FATFS在STM32上特別是由CubeMX工具移植變得簡(jiǎn)單,相對(duì)在其他芯片平臺(tái)沒(méi)有這個(gè)工具時(shí)趟径,清晰的了解移植的方法步驟變得更加重要了。

測(cè)試效果

在這里插入圖片描述

前提條件

FATFS移植需要做的:

  • 配置FATFS沽翔,裁剪相關(guān)功能
  • 完善使用操作系統(tǒng)時(shí)的互斥鎖接口
  • 完善內(nèi)存管理接口
  • 完善diskio.c中對(duì)存儲(chǔ)設(shè)備的操作接口

本工程,使用W25Q16BVspi flash芯片款筑,所以移植SFUD完善對(duì)FLASH的操作接口
本工程源碼

下載所需源碼

FATFS 文件系統(tǒng)

下載地址,可能需代理工具

SFUD萬(wàn)能驅(qū)動(dòng)

官方移植方法參考
本博客移植參考

加入工程

port目錄下皆是需要修改的的文件腋寨,diskio.c需配合disk_port.c做出微調(diào),其他無(wú)需修改

在這里插入圖片描述

接口驅(qū)動(dòng)

diskio.c調(diào)整如下:
包含驅(qū)動(dòng)接口頭文件disk_port.h
調(diào)用disk_drv_array里的相關(guān)函數(shù)

/*-----------------------------------------------------------------------*/
/* 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 == 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 */
)
{
  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磁盤(pán)驅(qū)動(dòng)接口

/**
 *  @file disk_port.c
 *
 *  @date 2021-01-05
 *
 *  @author aron566
 *
 *  @copyright None.
 *
 *  @brief 磁盤(pán)接口驅(qū)動(dòng)映射
 *
 *  @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磁盤(pán)狀態(tài)讀取
  * @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磁盤(pán)初始化
  * @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磁盤(pán)讀取指定扇區(qū)數(shù)的數(shù)據(jù)到緩沖區(qū)
  * @param   [out]buff 緩沖區(qū)
  * @param   [in]sector 起始扇區(qū)號(hào)
  * @param   [in]count 扇區(qū)數(shù)
  * @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磁盤(pán)寫(xiě)入數(shù)據(jù)到指定扇區(qū)數(shù)
  * @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磁盤(pán)特殊操作
  * @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;/**< 擦除扇區(qū)的最小個(gè)數(shù)(1*512Byte = 2 PAGE SIZE),per 32K/64K block size to erase*/
            return RES_OK;
        case CTRL_TRIM:
            return RES_PARERR;/**< 通知扇區(qū)數(shù)據(jù)不使用--未開(kāi)啟功能*/
        default:
            break;
    }
    return RES_PARERR;
}

/** Public application code --------------------------------------------------*/
/*******************************************************************************
*
*       Public code
*
********************************************************************************
*/
/**
  ******************************************************************
  * @brief   獲取當(dāng)前時(shí)間秒數(shù)
  * @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磁盤(pán)驅(qū)動(dòng)接口

/**
 *  @file disk_port.h
 *
 *  @date 2021-01-04
 *
 *  @author aron566
 *
 *  @brief 磁盤(pán)接口驅(qū)動(dòng)
 *  
 *  @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 -----------------------------------------------------*/
/*磁盤(pán)狀態(tài)讀取*/
typedef DSTATUS(*pdisk_status_func)(void);
/*磁盤(pán)初始化*/
typedef DSTATUS(*pdisk_initialize_func)(void);
/*磁盤(pán)讀取數(shù)據(jù)*/
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 */
);
/*磁盤(pán)寫(xiě)入數(shù)據(jù)*/
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 */
);
/*磁盤(pán)控制*/
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];/**< 磁盤(pán)設(shè)備驅(qū)動(dòng)接口*/

extern osMutexDef_t disk_mutex_array[DEV_TYPE_MAX];/**< 磁盤(pán)同步鎖*/
/** Exported functions prototypes --------------------------------------------*/
DWORD disk_get_rtc_time_s(void);
#ifdef __cplusplus ///<end extern c
}
#endif
#endif
/******************************** End of file *********************************/

ffsystem.cFATFS的信號(hào)量動(dòng)態(tài)內(nèi)存管理

/*------------------------------------------------------------------------*/
/* 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   獲取當(dāng)前時(shí)間秒數(shù)
  * @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.hFATFS配置文件

/*---------------------------------------------------------------------------/
/  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/**< 邏輯驅(qū)動(dòng)號(hào)就是掛載的設(shè)備號(hào)0:昌执,也對(duì)應(yīng)設(shè)備驅(qū)動(dòng)號(hào)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 ---*/

測(cè)試代碼

/**
 *  @file fatfs_opt.c
 *
 *  @date 2021-01-05
 *
 *  @author aron566
 *
 *  @copyright None.
 *
 *  @brief 文件系統(tǒng)操作
 *
 *  @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];/**< 掛載工作內(nèi)存,不可放入線(xiàn)程,占用內(nèi)存太大*/
static FATFS fsobject;/**< 磁盤(pán)掛載對(duì)象,不可放入線(xiàn)程,占用內(nèi)存太大*/
static FIL fp;/**< 文件對(duì)象,不可放入線(xiàn)程,占用內(nèi)存太大*/
/** Private function prototypes ----------------------------------------------*/

/** Private user code --------------------------------------------------------*/

/** Private application code -------------------------------------------------*/
/*******************************************************************************
*
*       Static code
*
********************************************************************************
*/

/** Public application code --------------------------------------------------*/
/*******************************************************************************
*
*       Public code
*
********************************************************************************
*/
/**
  ******************************************************************
  * @brief   測(cè)試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;/*邏輯驅(qū)動(dòng)器號(hào)*/
//  parm.align = 512; /*分配扇區(qū)大小*/
//  parm.n_root = 0;
//  parm.au_size = 0;
//  printf("fatfs test start.\n");
//  /* 格式化文件系統(tǒng) */
//  res = f_mkfs("3:", &parm, work, sizeof(work));//"3:"是卷標(biāo),來(lái)自于 #define SPI_FLASH       0
//  if (res)
//  {
//      printf("format faild.\n");
//      return ;
//  }
//  else
//  {
//      printf("format ok.\n");
//  }

  /*掛載*/
    FRESULT res;
    res = f_mount(&fsobject,  "3:",  1);  /**< 掛載文件系統(tǒng), "3:"就是掛載的設(shè)備號(hào)為3的設(shè)備,1立即執(zhí)行掛載*/

    if(res == FR_NO_FILESYSTEM)  /**< FR_NO_FILESYSTEM值為13,表示沒(méi)有有效的設(shè)備*/
    {
        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);/**< 取消文件系統(tǒng)*/
        res = f_mount(&fsobject, "3:", 1);/**< 掛載文件系統(tǒng)*/
    }
     printf("res = %d\r\n", res);
  
    /*創(chuàng)建文件*/
    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);
  
    /*關(guān)閉文件*/
    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 *********************************/
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末懂拾,一起剝皮案震驚了整個(gè)濱河市煤禽,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌岖赋,老刑警劉巖檬果,帶你破解...
    沈念sama閱讀 219,110評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異唐断,居然都是意外死亡选脊,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,443評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén)脸甘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)恳啥,“玉大人,你說(shuō)我怎么就攤上這事丹诀〗谴纾” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,474評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵忿墅,是天一觀(guān)的道長(zhǎng)。 經(jīng)常有香客問(wèn)我沮峡,道長(zhǎng)疚脐,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,881評(píng)論 1 295
  • 正文 為了忘掉前任邢疙,我火速辦了婚禮棍弄,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘疟游。我一直安慰自己呼畸,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,902評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布颁虐。 她就那樣靜靜地躺著蛮原,像睡著了一般。 火紅的嫁衣襯著肌膚如雪另绩。 梳的紋絲不亂的頭發(fā)上儒陨,一...
    開(kāi)封第一講書(shū)人閱讀 51,698評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音笋籽,去河邊找鬼蹦漠。 笑死,一個(gè)胖子當(dāng)著我的面吹牛车海,可吹牛的內(nèi)容都是我干的笛园。 我是一名探鬼主播,決...
    沈念sama閱讀 40,418評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼研铆!你這毒婦竟也來(lái)了埋同?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,332評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤蚜印,失蹤者是張志新(化名)和其女友劉穎莺禁,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體窄赋,經(jīng)...
    沈念sama閱讀 45,796評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡哟冬,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,968評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了忆绰。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片浩峡。...
    茶點(diǎn)故事閱讀 40,110評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖错敢,靈堂內(nèi)的尸體忽然破棺而出翰灾,到底是詐尸還是另有隱情,我是刑警寧澤稚茅,帶...
    沈念sama閱讀 35,792評(píng)論 5 346
  • 正文 年R本政府宣布纸淮,位于F島的核電站,受9級(jí)特大地震影響亚享,放射性物質(zhì)發(fā)生泄漏咽块。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,455評(píng)論 3 331
  • 文/蒙蒙 一欺税、第九天 我趴在偏房一處隱蔽的房頂上張望侈沪。 院中可真熱鬧,春花似錦晚凿、人聲如沸亭罪。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 32,003評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)应役。三九已至,卻和暖如春燥筷,著一層夾襖步出監(jiān)牢的瞬間扛吞,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,130評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工荆责, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留滥比,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,348評(píng)論 3 373
  • 正文 我出身青樓做院,卻偏偏與公主長(zhǎng)得像盲泛,于是被迫代替她去往敵國(guó)和親濒持。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,047評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容