USB MSC类存储设备及FatfsR0.14移植
USB MSC类存储设备及FatfsR0.14移植
- 效果演示
- 配置说明
- USB MSC类配置
- FatFs移植
- FatFs的配置
- 驱动接口
- FatFs测试
- USB MSC驱动接口完善
效果演示
这里演示了,FatFs挂载SPI Flash设备,创建一个test.txt文件,写入Hello,World!
字符串,之后PC打开枚举成功的U盘设备,打开这个文本文件,将其内容改为了Aron566,2022-09-28
配置说明
硬件情况:
- STM32H743VIT6
- 外部SPI Flash GD25Q64C 8MB的空间大小
Flash信息:
* - 页面编程时间:典型值0.6ms* - 扇区擦除时间:典型值50ms* - 块擦除时间:典型值0.15/0.20s* - 芯片擦除时间:典型值25s* - 统一的4K字节扇区* - 统一的32/64K字节块* - 512Bytes编程* - 10W次编程
这里用到了开源驱动组件SFUD
,移植方法可以查看这里:https://blog.csdn.net/weixin_42892101/article/details/106588125
USB MSC类配置
MSC类的配置,可以实用CubeMX直接配置生成,网上有太多图文配置教程了,这里不多写,配置好之后
编译运行,USB连接PC电脑,应该会弹出一个待格式化的U盘
FatFs移植
移植FatFs建议首先确定自己的Flash驱动没问题
带RTOS的移植方法可以查看这里:https://blog.csdn.net/weixin_42892101/article/details/112245585
本次移植不带RTOS
工程中新建目录:FatFs用于存放源码,增加port
目录存放移植接口文件,src
目录存放源码
FatFs的配置
配置中,FF_CODE_PAGE改为437、FF_LFN_UNICODE为0,改为中文简体936 + UTF-8编码会乱码,知道的朋友可以说下
/*---------------------------------------------------------------------------/
/ FatFs Functional Configurations
/---------------------------------------------------------------------------*/#define FFCONF_DEF 86631 /* 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 1
/* 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 0
/* 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 0
/* 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) */#define FF_USE_STRFUNC 0
#define FF_PRINT_LLI 0
#define FF_PRINT_FLOAT 1
#define FF_STRF_ENCODE 3
/* FF_USE_STRFUNC switches string 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/2makes f_printf() support floating point argument. These features want C99 or later.
/ When FF_LFN_UNICODE >= 1 with LFN enabled, string 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 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 0
/* 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 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
/* Number of volumes (logical drives) to be used. (1-10) */#define FF_STR_VOLUME_ID 8
#define FF_VOLUME_STRS "RAM","NAND","CF","SD","SD2","USB","USB2","USB3","HHT_Disk"
/* 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 1
/* 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 <somertos.h> // O/S definitions */
#define FF_FS_REENTRANT 0
#define FF_FS_TIMEOUT 1000
#define FF_SYNC_t HANDLE
/* 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. *//*--- End of configuration options ---*/
驱动接口
移植接口文件disk_port.c
主要用于提供FatFs的diskio.c
读取、写入、擦除、控制接口,RTC时钟接口(获取秒)
/*** @file disk_port.c** @date 2022年09月27日 11:19:56 星期二** @author aron566** @copyright Copyright (c) 2022 aron566 <aron566@163.com>.** @brief None.** @details None.** @version v1.0.0*/
/** Includes -----------------------------------------------------------------*/
/* Private includes ----------------------------------------------------------*/
#include "disk_port.h"
#include <sfud.h>
#include "main.h"
#include "RTC_Port.h"
/** Use C compiler -----------------------------------------------------------*/
#ifdef __cplusplus ///< use C compiler
extern "C" {#endif
/** Private macros -----------------------------------------------------------*//** Private typedef ----------------------------------------------------------*//** Private constants --------------------------------------------------------*/
/** Public variables ---------------------------------------------------------*//** Private function prototypes ----------------------------------------------*/
/*** @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 user code --------------------------------------------------------*//** Private application code -------------------------------------------------*//** 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_t flash = sfud_get_device(SFUD_GD25Q64C_DEVICE1_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_t flash = sfud_get_device(SFUD_GD25Q64C_DEVICE1_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_t flash = sfud_get_device(SFUD_GD25Q64C_DEVICE1_INDEX);if(flash == NULL){return RES_PARERR;}uint8_t status;sfud_read_status(flash, &status);sfud_err result = sfud_read(flash, sector * FF_MAX_SS, FF_MAX_SS * 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_t flash = sfud_get_device(SFUD_GD25Q64C_DEVICE1_INDEX);if(flash == NULL){return RES_PARERR;}uint8_t status;sfud_read_status(flash, &status);if(sfud_erase(flash, sector * FF_MAX_SS, FF_MAX_SS * count) != SFUD_SUCCESS){return RES_ERROR;}sfud_read_status(flash, &status);sfud_err result = sfud_write(flash, sector * FF_MAX_SS, FF_MAX_SS * 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 * 4;/**< PAGE SIZE:256,SECTOR SIZE:4KB,BLOCK SIZE:32/64KB,GD25Q64C TOTOAL SIZE:512*16KB*/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
*
********************************************************************************
*//** 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 (DWORD)RTC_Port_Get_TimeStamp();
}#ifdef __cplusplus ///<end extern c
}
#endif
/******************************** End of file *********************************/
disk_port.h
/*** @file disk_port.h** @date 2022年09月27日 11:20:15 星期二** @author Copyright (c) 2022 aron566 <aron566@163.com>.** @brief FatFs驱动接口.** @version v1.0.0*/
#ifndef _DISK_PORT_H
#define _DISK_PORT_H
/** Includes -----------------------------------------------------------------*/
#include <stdint.h> /**< need 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 */
// #include <stdalign.h> /**< need alignof */
// #include <stdarg.h> /**< need va_start */
/** Private includes ---------------------------------------------------------*/#include "ff.h"
#include "diskio.h"
/** Use C compiler -----------------------------------------------------------*/
#ifdef __cplusplus ///< use C compiler
extern "C" {#endif
/** Private defines ----------------------------------------------------------*//** Exported typedefines -----------------------------------------------------*/
/** Exported constants -------------------------------------------------------*//** Exported macros-----------------------------------------------------------*/
/** Exported variables -------------------------------------------------------*/
/** Exported functions prototypes --------------------------------------------*/
/* 磁盘状态读取 */
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 /* Example: Map SPI flash to physical drive 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 --------------------------------------------*//*** @brief 获取RTC时间戳** @return DWORD*/
DWORD disk_get_rtc_time_s(void);#ifdef __cplusplus ///<end extern c
}
#endif
#endif
/******************************** End of file *********************************/
diskio.c
修改如下:
/*-----------------------------------------------------------------------*/
/* 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"/* 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 *//*-----------------------------------------------------------------------*/
/* Get Drive Status */
/*-----------------------------------------------------------------------*/DSTATUS disk_status (BYTE pdrv /* Physical drive nmuber to identify the drive */
)
{switch (pdrv) {case DEV_RAM :case DEV_MMC :case DEV_USB :case DEV_SPI_FLASH:return disk_drv_array[pdrv].get_disk_status_port();}return STA_NOINIT;
}/*-----------------------------------------------------------------------*/
/* Inidialize a Drive */
/*-----------------------------------------------------------------------*/DSTATUS disk_initialize (BYTE pdrv /* Physical drive nmuber to identify the drive */
)
{switch (pdrv) {case DEV_RAM :case DEV_MMC :case DEV_USB :case DEV_SPI_FLASH:return disk_drv_array[pdrv].disk_init_port();}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 */
)
{switch (pdrv) {case DEV_RAM :case DEV_MMC :case DEV_USB :case DEV_SPI_FLASH:return disk_drv_array[pdrv].disk_read_port(buff, sector, count);}return RES_PARERR;
}/*-----------------------------------------------------------------------*/
/* 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 */
)
{switch (pdrv) {case DEV_RAM :case DEV_MMC :case DEV_USB :case DEV_SPI_FLASH:return disk_drv_array[pdrv].disk_write_port(buff, sector, count);}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 */
)
{switch (pdrv) {case DEV_RAM :case DEV_MMC :case DEV_USB :case DEV_SPI_FLASH:return disk_drv_array[pdrv].disk_ioctl_port(cmd, buff);}return RES_PARERR;
}DWORD get_fattime (void)
{return disk_get_rtc_time_s();
}
FatFs测试
以上配置没问题的话可以用以下代码进行测试验证
static BYTE work[FF_MAX_SS];/**< 挂载工作内存,不可放入线程,占用内存太大 */
static FATFS fsobject;/**< 磁盘挂载对象,不可放入线程,占用内存太大 */
static FIL fp;/**< 文件对象,不可放入线程,占用内存太大 */
/*** @brief 测试fatfs**/
static void FatFs_Test_Code(void)
{/* 挂载文件系统, "3:"就是挂载的设备号为3 SPI的设备,1立即执行挂载 */FRESULT res;res = f_mount(&fsobject, "3:", 1);/* 没有文件系统进行格式化 */if(res == FR_NO_FILESYSTEM){printf("FR_NO_FILESYSTEM\r\n");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);/**< 挂载文件系统 */}if(FR_OK != res){printf("f_mount error.\r\n");return;}/* 尝试打开文件 */res = f_open(&fp, "3:/test.txt", FA_CREATE_NEW|FA_WRITE|FA_READ);if(res){if(res == FR_EXIST){printf("the file is existed.\r\n");res = f_open(&fp, "3:/test.txt", FA_WRITE|FA_READ);}}else{printf("f_open file ok.\r\n");}if(FR_OK != res){printf("f_open error.\r\n");return;}/* 读取文件大小 */FSIZE_t fsize;fsize = f_size(&fp);if(0 < fsize){printf("file size:%llu Bytes.\r\n", fsize);BYTE buf[50];memset(buf, 0, 50);f_lseek(&fp, 0);UINT read_size;res = f_read(&fp, buf, fsize > 50 ? 50 : fsize, &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("\n%s\n", buf);}else{/* write a message */UINT write_size;res = f_write(&fp, "Hello,World!", 12, &write_size);if(write_size == 12){printf("write ok!\r\n");}else{printf("write faild!\r\n");}}/* 关闭文件 */f_close(&fp);
}
USB MSC驱动接口完善
usbd_storage_if.c
#define STORAGE_LUN_NBR 1
#define STORAGE_BLK_NBR (4096*4) //8MB总大小(8*1024*1024)/512
#define STORAGE_BLK_SIZ 512 //定义的扇区大小
读写接口完善即可
/*** @brief Reads data from the medium.* @param lun: Logical unit number.* @param buf: data buffer.* @param blk_addr: Logical block address.* @param blk_len: Blocks number.* @retval USBD_OK if all operations are OK else USBD_FAIL*/
int8_t STORAGE_Read_FS(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len)
{/* USER CODE BEGIN 6 */UNUSED(lun);// UNUSED(buf);// UNUSED(blk_addr);// UNUSED(blk_len);if(disk_drv_array[DEV_SPI_FLASH].disk_read_port(buf, blk_addr, blk_len) != RES_OK){printf("read blk_addr %u blk_len %u error.\r\n", blk_addr, blk_len);}return (USBD_OK);/* USER CODE END 6 */
}/*** @brief Writes data into the medium.* @param lun: Logical unit number.* @param buf: data buffer.* @param blk_addr: Logical block address.* @param blk_len: Blocks number.* @retval USBD_OK if all operations are OK else USBD_FAIL*/
int8_t STORAGE_Write_FS(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len)
{/* USER CODE BEGIN 7 */UNUSED(lun);// UNUSED(buf);// UNUSED(blk_addr);// UNUSED(blk_len);if(disk_drv_array[DEV_SPI_FLASH].disk_write_port(buf, blk_addr, blk_len) != RES_OK){printf("write blk_addr %u blk_len %u error.\r\n", blk_addr, blk_len);}return (USBD_OK);/* USER CODE END 7 */
}
USB MSC类存储设备及FatfsR0.14移植相关推荐
- solaris下使用USB 海量存储设备
第8 章• 使用USB 设备(任务) 139 从Solaris 10 1/06 发行版开始,vold 可自动挂载热插拔设备.有关更多信息,请参见第 124 页中的"vold 用于识别热插拔U ...
- 在Linux系统中存储设备的两种表示方法
作者:北南南北 来自:LinuxSir.Org 摘要: 硬盘和硬盘分区在Linux都表示为设备,按我们通俗的说法来说,就是怎么来表示或描述硬盘和或硬盘分区,但这种描述应该是科学和具体的:比如IDE硬盘 ...
- 02 MSC类设备-基础篇(二)
上一篇: https://blog.csdn.net/qq_40088639/article/details/110489923 四.Bulk-Only Transport协议传输模型 分析BusHo ...
- 01 MSC类设备-基础篇(一)
一.简介 在USB协议中,规定了一类大容量存储设备(Mass Storage Device Class)协议.常见的USB大容量设备有:U盘.USB移动硬盘.USB移动光驱.USB读卡器.USB打印机 ...
- ubuntu14.04禁用USB外存储设备
ubuntu 14.04中禁用usb外存储设备: 在网上找了很多方法,大概都是下面的命令,而实际测试的时候没有什么作用. gsettings set org.gnome.desktop.media-h ...
- 开始计算机USB存储功能,USB存储设备禁用怎么设置
因为有些情况下我们必须得禁止USB存储设备,特别是涉及到当文件被泄漏或者复制时,那如何设置禁用USB存储设备呢?下面是学习啦小编为大家介绍禁用USB存储设备的设置方法,欢迎大家阅读. 禁用USB存储设 ...
- 将windows系统装到USB存储设备
将windows系统装到USB存储设备 需求: 1)一般公司比较规范,计算机系统有严格的限制策略,如果自己不懂得如何更改或者没有权限更改,将极其不便. 2)计划在家里完成在公司未完成的事,甚至异地出差 ...
- 用 C# 编写 USB 存储设备使用痕迹检测和删除工具
编写 USB 存储设备使用痕迹检测和删除工具 (C# Windows Form 编程练习) [版权所有 邱秋 2014 metaphysis@yeah.net, 转载请注明出处] 第一节 准备知识 之 ...
- 树莓派USB存储设备自动挂载并通过脚本实现自动拷贝,自动播放视频,脚本自动升级等功能...
需求: 首先需要树莓派自动挂载USB设备,然后扫描USB指定目录下文件,将相关文件拷贝至树莓派指定目录,然后通过omxplayer循环播放新拷贝文件视频 1. 树莓派实现USB存储设备自动挂载 树莓派 ...
最新文章
- tensorflow.python.framework.errors_impl.InvalidArgumentError: 2 root error(s) found.
- 【Spring注解驱动开发】自学java和三大框架要多久
- QuartZ.net 常用配置说明
- redis的zset的底层实现_Redis(三)--- Redis的五大数据类型的底层实现
- python filecmp
- Dijkstra+DFS模板总结
- python-rrdtool python-pyrrd
- 软件构建中的设计(一)
- dijit.layout.ContentPane--dojo学习
- 机器学习之推荐算法分类
- linux中wifi抓取包,使用wireshark捕获wifi包(linux)
- HBuilderX踩坑记录(1)—— vivo iqoo z1开启adb调试
- android号牌号码识别新能源,Android离线版车牌号识别相关问题
- Substance Painter 创建头发实验
- yolov5检测限定长宽比检测范围的目标
- Android 短视频编辑开发之摄像头预览实时美颜(三)
- 云南一脸通行业解决方案、钉钉智慧食堂、智慧餐厅、智慧工地解决方案
- 管理之道(十) - 你还在崇拜交付速度吗?
- 可汗学院统计学 task 3
- 机器学习 逻辑回归算法应用案例