[RISC-V MCU 应用开发] 【RISC-V MCU CH32V103测评8】+串行FLASH芯片上FATFS系统

[复制链接]
 楼主| xyz549040622 发表于 2020-12-8 22:55 | 显示全部楼层 |阅读模式
本帖最后由 xyz549040622 于 2020-12-9 15:23 编辑

不知道为什么刚开始一直没有成功,正当准备放弃的时候自己又好了,总之是十分诡异啊。
首先去fatfs官网下载最新版的文件,最新版是R0.14a,链接如下:
http://elm-chan.org/fsw/ff/00index_e.html
然后是w25q16的驱动文件前面已经测试完毕了,看前面的测评**即可。
全部分fatfs文件包如下:
614685fd0783fa1569.png
我们需要进行的是diskio.c文件的修改和ffconf.h文件的配置。
首先需要进行的是头文件的包含,不知道为什么头文件放在diskio.c中老是报错,我干脆都放在diskio.h中了。
  1. #include "ff.h"         /* Obtains integer types */
  2. #include "w25qxx.h"
  3. #include "usart.h"
然后是diskio.c的修改:
  1. /*-----------------------------------------------------------------------*/
  2. /* Low level disk I/O module SKELETON for FatFs     (C)ChaN, 2019        */
  3. /*-----------------------------------------------------------------------*/
  4. /* If a working storage control module is available, it should be        */
  5. /* attached to the FatFs via a glue function rather than modifying it.   */
  6. /* This is an example of glue functions to attach various exsisting      */
  7. /* storage control modules to the FatFs module with a defined API.       */
  8. /*-----------------------------------------------------------------------*/


  9. #include "diskio.h"     /* Declarations of disk functions */


  10. /* Definitions of physical drive number for each drive */
  11. //#define DEV_RAM                0        /* Example: Map Ramdisk to physical drive 0 */
  12. //#define DEV_MMC                1        /* Example: Map MMC/SD card to physical drive 1 */
  13. //#define DEV_USB                2        /* Example: Map USB MSD to physical drive 2 */

  14. /* 为每个设备定义一个物理编号 */
  15. #define ATA             1     // 预留SD卡使用
  16. #define SPI_FLASH       0     // 外部SPI Flash
  17. /*-----------------------------------------------------------------------*/
  18. /* Get Drive Status                                                      */
  19. /*-----------------------------------------------------------------------*/

  20. DSTATUS disk_status (
  21.         BYTE pdrv                /* Physical drive nmuber to identify the drive */
  22. )
  23. {

  24.     DSTATUS status = STA_NOINIT;

  25.     switch (pdrv)
  26.     {
  27.         case ATA:   /* SD CARD */
  28.             break;

  29.         case SPI_FLASH:
  30.           /* SPI Flash状态检测:读取SPI Flash 设备ID */
  31.           if(W25Q16 == SPI_Flash_ReadID())
  32.           {
  33.             /* 设备ID读取结果正确 */
  34.             status &= ~STA_NOINIT;
  35.           }
  36.           else
  37.           {
  38.             /* 设备ID读取结果错误 */
  39.             status = STA_NOINIT;;
  40.           }
  41.           break;

  42.         default:
  43.             status = STA_NOINIT;
  44.             break;
  45.     }
  46.     return status;
  47. }



  48. /*-----------------------------------------------------------------------*/
  49. /* Inidialize a Drive                                                    */
  50. /*-----------------------------------------------------------------------*/

  51. DSTATUS disk_initialize (
  52.         BYTE pdrv                                /* Physical drive nmuber to identify the drive */
  53. )
  54. {
  55.     uint16_t i;
  56.       DSTATUS status = STA_NOINIT;
  57.       switch (pdrv)
  58.       {
  59.           case ATA:            /* SD CARD */
  60.               break;

  61.           case SPI_FLASH:    /* SPI Flash */
  62.             /* 初始化SPI Flash */
  63.               SPI_Flash_Init();
  64.             /* 延时一小段时间 */
  65. //            i=500;
  66. //            while(--i);
  67.             /* 唤醒SPI Flash */
  68. //            SPI_Flash_WAKEUP();
  69.             /* 获取SPI Flash芯片状态 */
  70.             status=disk_status(SPI_FLASH);
  71.             break;

  72.           default:
  73.             status = STA_NOINIT;
  74.             break;
  75.       }
  76.       return status;
  77. }



  78. /*-----------------------------------------------------------------------*/
  79. /* Read Sector(s)                                                        */
  80. /*-----------------------------------------------------------------------*/

  81. DRESULT disk_read (
  82.         BYTE pdrv,                /* Physical drive nmuber to identify the drive */
  83.         BYTE *buff,                /* Data buffer to store read data */
  84.         LBA_t sector,        /* Start sector in LBA */
  85.         UINT count                /* Number of sectors to read */
  86. )
  87. {
  88.     DRESULT status = RES_PARERR;
  89.     switch (pdrv)
  90.     {
  91.         case ATA:   /* SD CARD */
  92.             break;

  93.         case SPI_FLASH:
  94.             SPI_Flash_Read(buff, sector <<12, count<<12);
  95.           status = RES_OK;
  96.             break;

  97.         default:
  98.             status = RES_PARERR;
  99.             break;
  100.     }
  101.     return status;
  102. }



  103. /*-----------------------------------------------------------------------*/
  104. /* Write Sector(s)                                                       */
  105. /*-----------------------------------------------------------------------*/

  106. #if FF_FS_READONLY == 0

  107. DRESULT disk_write (
  108.         BYTE pdrv,                        /* Physical drive nmuber to identify the drive */
  109.         const BYTE *buff,        /* Data to be written */
  110.         LBA_t sector,                /* Start sector in LBA */
  111.         UINT count                        /* Number of sectors to write */
  112. )
  113. {
  114.       DRESULT status = RES_PARERR;
  115.       if (!count) {
  116.           return RES_PARERR;      /* Check parameter */
  117.       }

  118.       switch (pdrv)
  119.       {
  120.           case ATA:   /* SD CARD */
  121.               break;

  122.           case SPI_FLASH:
  123. //            write_addr = sector<<12;
  124.             SPI_Flash_Erase_Sector(sector);
  125.             SPI_Flash_Write((uint8_t *)buff,sector<<12,count<<12);
  126.             status = RES_OK;
  127.             break;

  128.           default:
  129.             status = RES_PARERR;
  130.             break;
  131.       }
  132.       return status;
  133. }

  134. #endif


  135. /*-----------------------------------------------------------------------*/
  136. /* Miscellaneous Functions                                               */
  137. /*-----------------------------------------------------------------------*/

  138. DRESULT disk_ioctl (
  139.         BYTE pdrv,                /* Physical drive nmuber (0..) */
  140.         BYTE cmd,                /* Control code */
  141.         void *buff                /* Buffer to send/receive control data */
  142. )
  143. {
  144.     DRESULT status = RES_PARERR;
  145.     switch (pdrv)
  146.     {
  147.         case ATA:   /* SD CARD */
  148.             break;

  149.         case SPI_FLASH:
  150.             switch (cmd)
  151.             {
  152.                 /* 扇区数量:1536*4096/1024/1024=6(MB) */
  153.                 case GET_SECTOR_COUNT:
  154.                     *(DWORD * )buff = 512;
  155.                     break;
  156.                 /* 扇区大小  */
  157.                 case GET_SECTOR_SIZE :
  158.                     *(WORD * )buff = 4096;
  159.                     break;
  160.                 /* 同时擦除扇区个数 */
  161.                 case GET_BLOCK_SIZE :
  162.                     *(DWORD * )buff = 1;
  163.                     break;
  164.             }
  165.             status = RES_OK;
  166.             break;

  167.         default:
  168.             status = RES_PARERR;
  169.             break;
  170.     }
  171.     return status;
  172. }

  173. DWORD get_fattime(void) {
  174.     /* 返回当前时间戳 */
  175.     return    ((DWORD)(2015 - 1980) << 25)  /* Year 2015 */
  176.             | ((DWORD)1 << 21)              /* Month 1 */
  177.             | ((DWORD)1 << 16)              /* Mday 1 */
  178.             | ((DWORD)0 << 11)              /* Hour 0 */
  179.             | ((DWORD)0 << 5)                 /* Min 0 */
  180.             | ((DWORD)0 >> 1);              /* Sec 0 */
  181. }
ffconf.h文件中宏定义的配置:
  1. /*---------------------------------------------------------------------------/
  2. /  FatFs Functional Configurations
  3. /---------------------------------------------------------------------------*/

  4. #define FFCONF_DEF        80196        /* Revision ID */

  5. /*---------------------------------------------------------------------------/
  6. / Function Configurations
  7. /---------------------------------------------------------------------------*/

  8. #define FF_FS_READONLY        0
  9. /* This option switches read-only configuration. (0:Read/Write or 1:Read-only)
  10. /  Read-only configuration removes writing API functions, f_write(), f_sync(),
  11. /  f_unlink(), f_mkdir(), f_chmod(), f_rename(), f_truncate(), f_getfree()
  12. /  and optional writing functions as well. */


  13. #define FF_FS_MINIMIZE        0
  14. /* This option defines minimization level to remove some basic API functions.
  15. /
  16. /   0: Basic functions are fully enabled.
  17. /   1: f_stat(), f_getfree(), f_unlink(), f_mkdir(), f_truncate() and f_rename()
  18. /      are removed.
  19. /   2: f_opendir(), f_readdir() and f_closedir() are removed in addition to 1.
  20. /   3: f_lseek() function is removed in addition to 2. */


  21. #define FF_USE_STRFUNC        0
  22. /* This option switches string functions, f_gets(), f_putc(), f_puts() and f_printf().
  23. /
  24. /  0: Disable string functions.
  25. /  1: Enable without LF-CRLF conversion.
  26. /  2: Enable with LF-CRLF conversion. */


  27. #define FF_USE_FIND                0
  28. /* This option switches filtered directory read functions, f_findfirst() and
  29. /  f_findnext(). (0:Disable, 1:Enable 2:Enable with matching altname[] too) */


  30. #define FF_USE_MKFS                1
  31. /* This option switches f_mkfs() function. (0:Disable or 1:Enable) */


  32. #define FF_USE_FASTSEEK        0
  33. /* This option switches fast seek function. (0:Disable or 1:Enable) */


  34. #define FF_USE_EXPAND        0
  35. /* This option switches f_expand function. (0:Disable or 1:Enable) */


  36. #define FF_USE_CHMOD        0
  37. /* This option switches attribute manipulation functions, f_chmod() and f_utime().
  38. /  (0:Disable or 1:Enable) Also FF_FS_READONLY needs to be 0 to enable this option. */


  39. #define FF_USE_LABEL        0
  40. /* This option switches volume label functions, f_getlabel() and f_setlabel().
  41. /  (0:Disable or 1:Enable) */


  42. #define FF_USE_FORWARD        0
  43. /* This option switches f_forward() function. (0:Disable or 1:Enable) */


  44. /*---------------------------------------------------------------------------/
  45. / Locale and Namespace Configurations
  46. /---------------------------------------------------------------------------*/

  47. #define FF_CODE_PAGE        936
  48. /* This option specifies the OEM code page to be used on the target system.
  49. /  Incorrect code page setting can cause a file open failure.
  50. /
  51. /   437 - U.S.
  52. /   720 - Arabic
  53. /   737 - Greek
  54. /   771 - KBL
  55. /   775 - Baltic
  56. /   850 - Latin 1
  57. /   852 - Latin 2
  58. /   855 - Cyrillic
  59. /   857 - Turkish
  60. /   860 - Portuguese
  61. /   861 - Icelandic
  62. /   862 - Hebrew
  63. /   863 - Canadian French
  64. /   864 - Arabic
  65. /   865 - Nordic
  66. /   866 - Russian
  67. /   869 - Greek 2
  68. /   932 - Japanese (DBCS)
  69. /   936 - Simplified Chinese (DBCS)
  70. /   949 - Korean (DBCS)
  71. /   950 - Traditional Chinese (DBCS)
  72. /     0 - Include all code pages above and configured by f_setcp()
  73. */


  74. #define FF_USE_LFN                2
  75. #define FF_MAX_LFN                255
  76. /* The FF_USE_LFN switches the support for LFN (long file name).
  77. /
  78. /   0: Disable LFN. FF_MAX_LFN has no effect.
  79. /   1: Enable LFN with static  working buffer on the BSS. Always NOT thread-safe.
  80. /   2: Enable LFN with dynamic working buffer on the STACK.
  81. /   3: Enable LFN with dynamic working buffer on the HEAP.
  82. /
  83. /  To enable the LFN, ffunicode.c needs to be added to the project. The LFN function
  84. /  requiers certain internal working buffer occupies (FF_MAX_LFN + 1) * 2 bytes and
  85. /  additional (FF_MAX_LFN + 44) / 15 * 32 bytes when exFAT is enabled.
  86. /  The FF_MAX_LFN defines size of the working buffer in UTF-16 code unit and it can
  87. /  be in range of 12 to 255. It is recommended to be set it 255 to fully support LFN
  88. /  specification.
  89. /  When use stack for the working buffer, take care on stack overflow. When use heap
  90. /  memory for the working buffer, memory management functions, ff_memalloc() and
  91. /  ff_memfree() exemplified in ffsystem.c, need to be added to the project. */


  92. #define FF_LFN_UNICODE        0
  93. /* This option switches the character encoding on the API when LFN is enabled.
  94. /
  95. /   0: ANSI/OEM in current CP (TCHAR = char)
  96. /   1: Unicode in UTF-16 (TCHAR = WCHAR)
  97. /   2: Unicode in UTF-8 (TCHAR = char)
  98. /   3: Unicode in UTF-32 (TCHAR = DWORD)
  99. /
  100. /  Also behavior of string I/O functions will be affected by this option.
  101. /  When LFN is not enabled, this option has no effect. */


  102. #define FF_LFN_BUF                255
  103. #define FF_SFN_BUF                12
  104. /* This set of options defines size of file name members in the FILINFO structure
  105. /  which is used to read out directory items. These values should be suffcient for
  106. /  the file names to read. The maximum possible length of the read file name depends
  107. /  on character encoding. When LFN is not enabled, these options have no effect. */


  108. #define FF_STRF_ENCODE        3
  109. /* When FF_LFN_UNICODE >= 1 with LFN enabled, string I/O functions, f_gets(),
  110. /  f_putc(), f_puts and f_printf() convert the character encoding in it.
  111. /  This option selects assumption of character encoding ON THE FILE to be
  112. /  read/written via those functions.
  113. /
  114. /   0: ANSI/OEM in current CP
  115. /   1: Unicode in UTF-16LE
  116. /   2: Unicode in UTF-16BE
  117. /   3: Unicode in UTF-8
  118. */


  119. #define FF_FS_RPATH                0
  120. /* This option configures support for relative path.
  121. /
  122. /   0: Disable relative path and remove related functions.
  123. /   1: Enable relative path. f_chdir() and f_chdrive() are available.
  124. /   2: f_getcwd() function is available in addition to 1.
  125. */


  126. /*---------------------------------------------------------------------------/
  127. / Drive/Volume Configurations
  128. /---------------------------------------------------------------------------*/

  129. #define FF_VOLUMES                1
  130. /* Number of volumes (logical drives) to be used. (1-10) */


  131. #define FF_STR_VOLUME_ID        0
  132. #define FF_VOLUME_STRS                "RAM","NAND","CF","SD","SD2","USB","USB2","USB3"
  133. /* FF_STR_VOLUME_ID switches support for volume ID in arbitrary strings.
  134. /  When FF_STR_VOLUME_ID is set to 1 or 2, arbitrary strings can be used as drive
  135. /  number in the path name. FF_VOLUME_STRS defines the volume ID strings for each
  136. /  logical drives. Number of items must not be less than FF_VOLUMES. Valid
  137. /  characters for the volume ID strings are A-Z, a-z and 0-9, however, they are
  138. /  compared in case-insensitive. If FF_STR_VOLUME_ID >= 1 and FF_VOLUME_STRS is
  139. /  not defined, a user defined volume string table needs to be defined as:
  140. /
  141. /  const char* VolumeStr[FF_VOLUMES] = {"ram","flash","sd","usb",...
  142. */


  143. #define FF_MULTI_PARTITION        0
  144. /* This option switches support for multiple volumes on the physical drive.
  145. /  By default (0), each logical drive number is bound to the same physical drive
  146. /  number and only an FAT volume found on the physical drive will be mounted.
  147. /  When this function is enabled (1), each logical drive number can be bound to
  148. /  arbitrary physical drive and partition listed in the VolToPart[]. Also f_fdisk()
  149. /  funciton will be available. */


  150. #define FF_MIN_SS                512
  151. #define FF_MAX_SS                4096
  152. /* This set of options configures the range of sector size to be supported. (512,
  153. /  1024, 2048 or 4096) Always set both 512 for most systems, generic memory card and
  154. /  harddisk. But a larger value may be required for on-board flash memory and some
  155. /  type of optical media. When FF_MAX_SS is larger than FF_MIN_SS, FatFs is configured
  156. /  for variable sector size mode and disk_ioctl() function needs to implement
  157. /  GET_SECTOR_SIZE command. */


  158. #define FF_LBA64                0
  159. /* This option switches support for 64-bit LBA. (0:Disable or 1:Enable)
  160. /  To enable the 64-bit LBA, also exFAT needs to be enabled. (FF_FS_EXFAT == 1) */


  161. #define FF_MIN_GPT                0x10000000
  162. /* Minimum number of sectors to switch GPT as partitioning format in f_mkfs and
  163. /  f_fdisk function. 0x100000000 max. This option has no effect when FF_LBA64 == 0. */


  164. #define FF_USE_TRIM                0
  165. /* This option switches support for ATA-TRIM. (0:Disable or 1:Enable)
  166. /  To enable Trim function, also CTRL_TRIM command should be implemented to the
  167. /  disk_ioctl() function. */



  168. /*---------------------------------------------------------------------------/
  169. / System Configurations
  170. /---------------------------------------------------------------------------*/

  171. #define FF_FS_TINY                0
  172. /* This option switches tiny buffer configuration. (0:Normal or 1:Tiny)
  173. /  At the tiny configuration, size of file object (FIL) is shrinked FF_MAX_SS bytes.
  174. /  Instead of private sector buffer eliminated from the file object, common sector
  175. /  buffer in the filesystem object (FATFS) is used for the file data transfer. */


  176. #define FF_FS_EXFAT                0
  177. /* This option switches support for exFAT filesystem. (0:Disable or 1:Enable)
  178. /  To enable exFAT, also LFN needs to be enabled. (FF_USE_LFN >= 1)
  179. /  Note that enabling exFAT discards ANSI C (C89) compatibility. */


  180. #define FF_FS_NORTC                0
  181. #define FF_NORTC_MON        1
  182. #define FF_NORTC_MDAY        1
  183. #define FF_NORTC_YEAR        2020
  184. /* The option FF_FS_NORTC switches timestamp functiton. If the system does not have
  185. /  any RTC function or valid timestamp is not needed, set FF_FS_NORTC = 1 to disable
  186. /  the timestamp function. Every object modified by FatFs will have a fixed timestamp
  187. /  defined by FF_NORTC_MON, FF_NORTC_MDAY and FF_NORTC_YEAR in local time.
  188. /  To enable timestamp function (FF_FS_NORTC = 0), get_fattime() function need to be
  189. /  added to the project to read current time form real-time clock. FF_NORTC_MON,
  190. /  FF_NORTC_MDAY and FF_NORTC_YEAR have no effect.
  191. /  These options have no effect in read-only configuration (FF_FS_READONLY = 1). */


  192. #define FF_FS_NOFSINFO        0
  193. /* If you need to know correct free space on the FAT32 volume, set bit 0 of this
  194. /  option, and f_getfree() function at first time after volume mount will force
  195. /  a full FAT scan. Bit 1 controls the use of last allocated cluster number.
  196. /
  197. /  bit0=0: Use free cluster count in the FSINFO if available.
  198. /  bit0=1: Do not trust free cluster count in the FSINFO.
  199. /  bit1=0: Use last allocated cluster number in the FSINFO if available.
  200. /  bit1=1: Do not trust last allocated cluster number in the FSINFO.
  201. */


  202. #define FF_FS_LOCK                0
  203. /* The option FF_FS_LOCK switches file lock function to control duplicated file open
  204. /  and illegal operation to open objects. This option must be 0 when FF_FS_READONLY
  205. /  is 1.
  206. /
  207. /  0:  Disable file lock function. To avoid volume corruption, application program
  208. /      should avoid illegal open, remove and rename to the open objects.
  209. /  >0: Enable file lock function. The value defines how many files/sub-directories
  210. /      can be opened simultaneously under file lock control. Note that the file
  211. /      lock control is independent of re-entrancy. */


  212. /* #include <somertos.h>        // O/S definitions */
  213. #define FF_FS_REENTRANT        0
  214. #define FF_FS_TIMEOUT        1000
  215. #define FF_SYNC_t                HANDLE
  216. /* The option FF_FS_REENTRANT switches the re-entrancy (thread safe) of the FatFs
  217. /  module itself. Note that regardless of this option, file access to different
  218. /  volume is always re-entrant and volume control functions, f_mount(), f_mkfs()
  219. /  and f_fdisk() function, are always not re-entrant. Only file/directory access
  220. /  to the same volume is under control of this function.
  221. /
  222. /   0: Disable re-entrancy. FF_FS_TIMEOUT and FF_SYNC_t have no effect.
  223. /   1: Enable re-entrancy. Also user provided synchronization handlers,
  224. /      ff_req_grant(), ff_rel_grant(), ff_del_syncobj() and ff_cre_syncobj()
  225. /      function, must be added to the project. Samples are available in
  226. /      option/syscall.c.
  227. /
  228. /  The FF_FS_TIMEOUT defines timeout period in unit of time tick.
  229. /  The FF_SYNC_t defines O/S dependent sync object type. e.g. HANDLE, ID, OS_EVENT*,
  230. /  SemaphoreHandle_t and etc. A header file for O/S definitions needs to be
  231. /  included somewhere in the scope of ff.h. */



  232. /*--- End of configuration options ---*/
这里有几点需要注意的:
首先是当配置为#define FF_FS_NORTC        0的时候,是需要get_fattime这个函数的,我们在ffconf.c中人为的配置get_fattime这个函数。
  1. DWORD get_fattime(void) {
  2.     /* 返回当前时间戳 */
  3.     return    ((DWORD)(2015 - 1980) << 25)  /* Year 2015 */
  4.             | ((DWORD)1 << 21)              /* Month 1 */
  5.             | ((DWORD)1 << 16)              /* Mday 1 */
  6.             | ((DWORD)0 << 11)              /* Hour 0 */
  7.             | ((DWORD)0 << 5)                 /* Min 0 */
  8.             | ((DWORD)0 >> 1);              /* Sec 0 */
  9. }
然后是配置为#define FF_CODE_PAGE        936的时候,是需要调用ffunicode.c的,这里面定义了很大的数组,超过了芯片的默认的范围,我这里偷懒,没有研究这个空间到底够不够,直接把涉及到的数组内容屏蔽掉,所以在程序中是无法定义汉字文件名的。


然后再main函数中写一个搜索目录的函数:
  1. FRESULT scan_files (
  2.     char* path        /* Start node to be scanned (***also used as work area***) */
  3. )
  4. {
  5.     FRESULT res;
  6.     DIR dir;
  7.     UINT i;
  8.     static FILINFO fno;


  9.     res = f_opendir(&dir, path);                       /* Open the directory */
  10.     if (res == FR_OK)
  11.     {
  12.         for (;;)
  13.         {
  14.             res = f_readdir(&dir, &fno);                   /* Read a directory item */
  15.             if (res != FR_OK || fno.fname[0] == 0) break;  /* Break on error or end of dir */
  16.             if (fno.fattrib & AM_DIR)//假如是文件夹
  17.             {                    /* It is a directory */
  18.                 i = strlen(path);//计算出路径长度
  19.                 sprintf(&path[i], "/%s", fno.fname);//文件名加到路径后面
  20.                 res = scan_files(path);                    /* Enter the directory */
  21.                 if (res != FR_OK) break;
  22.                 path[i] = 0;

  23.             }
  24.             else
  25.             {                                       /* It is a file. */
  26.                 printf("%s/%s\r\n", path, fno.fname);
  27.             }
  28.         }
  29.         f_closedir(&dir);
  30.     }

  31.     return res;
  32. }


主函数进行文件系统的测试:
  1.     printf("****** 这是一个SPI FLASH 文件系统实验 ******\r\n");
  2. //
  3.     printf("FLASH正在整体擦除....\r\n");
  4.     SPI_Flash_Erase_Chip();
  5.     printf("FLASH整体擦除完毕....\r\n");

  6.     //在外部SPI Flash挂载文件系统,文件系统挂载时会对SPI设备初始化
  7.     //初始化函数调用流程如下
  8.     //f_mount()->find_volume()->disk_initialize->SPI_FLASH_Init()
  9.     res_flash = f_mount(&fs,"0:",1);

  10.     if(res_flash==FR_OK)
  11.     {
  12.       printf("》文件系统挂载成功\r\n");
  13.     }
  14.     else
  15.     {
  16.       printf("!!文件系统挂载失败:(%d)\r\n",res_flash);
  17.     }

  18.     /*----------------------- 格式化测试 -----------------*/
  19.         /* 如果没有文件系统就格式化创建创建文件系统 */
  20.         if(res_flash == FR_NO_FILESYSTEM)
  21.         {
  22.             printf("》FLASH还没有文件系统,即将进行格式化...\r\n");
  23.         /* 格式化 */
  24.             res_flash=f_mkfs("0:",0,work,sizeof(work));

  25.             if(res_flash == FR_OK)
  26.             {
  27.                 printf("》FLASH已成功格式化文件系统。\r\n");
  28.           /* 格式化后,先取消挂载 */
  29.                 res_flash = f_mount(NULL,"1:",1);
  30.           /* 重新挂载   */
  31.                 res_flash = f_mount(&fs,"1:",1);
  32.             }
  33.             else
  34.             {
  35.                 printf("《《格式化失败。》》\r\n");
  36.                 while(1);
  37.             }
  38.         }
  39.       else if(res_flash!=FR_OK)
  40.       {
  41.         printf("!!外部Flash挂载文件系统失败。(%d)\r\n",res_flash);
  42.         printf("!!可能原因:SPI Flash初始化不成功。\r\n");
  43.         while(1);
  44.       }
  45.       else
  46.       {
  47.         printf("》文件系统挂载成功,可以进行读写测试\r\n");
  48.       }

  49.     strcpy(filename, "123");
  50.     res_flash = f_mkdir(filename);
  51.     if(res_flash==FR_OK)
  52.     {
  53.       printf("》文件夹%s创建成功\r\n",filename);
  54.     }
  55.     else if(res_flash==FR_EXIST)
  56.     {
  57.         printf("!!文件夹已存在:(%d)\r\n",res_flash);
  58.     }
  59.     else
  60.     {
  61.       printf("!!文件夹创建失败:(%d)\r\n",res_flash);
  62.     }

  63.     strcpy(filename, "123/456");
  64.     res_flash = f_mkdir(filename);
  65.     if(res_flash==FR_OK)
  66.     {
  67.         printf("》文件夹%s创建成功\r\n",filename);
  68.     }
  69.     else if(res_flash==FR_EXIST)
  70.     {
  71.         printf("!!文件夹已存在:(%d)\r\n",res_flash);
  72.     }
  73.     else
  74.     {
  75.       printf("!!文件夹创建失败:(%d)\r\n",res_flash);
  76.     }

  77.     strcpy(filename, "123/456/789");
  78.     res_flash = f_mkdir(filename);
  79.     if(res_flash==FR_OK)
  80.     {
  81.         printf("》文件夹%s创建成功\r\n",filename);
  82.     }
  83.     else if(res_flash==FR_EXIST)
  84.     {
  85.         printf("!!文件夹已存在:(%d)\r\n",res_flash);
  86.     }
  87.     else
  88.     {
  89.       printf("!!文件夹创建失败:(%d)\r\n",res_flash);
  90.     }

  91.     /*----------------------- 文件系统测试:写测试 -------------------*/
  92.         /* 打开文件,每次都以新建的形式打开,属性为可写 */
  93.         printf("\r\n****** 即将进行文件写入测试... ******\r\n");
  94.         res_flash = f_open(&fnew, "0:123/456/789/CH32V103x.txt",FA_CREATE_ALWAYS | FA_WRITE );
  95.         if ( res_flash == FR_OK )
  96.         {
  97.             printf("》打开/创建CH32V103x.txt文件成功,向文件写入数据。\r\n");
  98.         /* 将指定存储区内容写入到文件内 */
  99.             res_flash=f_write(&fnew,WriteBuffer,sizeof(WriteBuffer),&fnum);
  100.         if(res_flash==FR_OK)
  101.         {
  102.           printf("》文件写入成功,写入字节数据:%d\r\n",fnum);
  103.           printf("》向文件写入的数据为:\r\n%s\r\n",WriteBuffer);
  104.         }
  105.         else
  106.         {
  107.           printf("!!文件写入失败:(%d)\n",res_flash);
  108.         }
  109.             /* 不再读写,关闭文件 */
  110.         f_close(&fnew);
  111.         }
  112.         else
  113.         {
  114.             printf("!!打开/创建文件失败。\r\n");
  115.         }

  116.     /*------------------- 文件系统测试:读测试 --------------------------*/
  117.         printf("****** 即将进行文件读取测试... ******\r\n");
  118.         res_flash = f_open(&fnew, "0:123/456/789/CH32V103x.txt",FA_OPEN_EXISTING | FA_READ);
  119.         if(res_flash == FR_OK)
  120.         {
  121.             printf("》打开文件成功。\r\n");
  122.             res_flash = f_read(&fnew, ReadBuffer, sizeof(ReadBuffer), &fnum);
  123.         if(res_flash==FR_OK)
  124.         {
  125.           printf("》文件读取成功,读到字节数据:%d\r\n",fnum);
  126.           printf("》读取得的文件数据为:\r\n%s \r\n", ReadBuffer);
  127.         }
  128.         else
  129.         {
  130.           printf("!!文件读取失败:(%d)\n",res_flash);
  131.         }
  132.         }
  133.         else
  134.         {
  135.             printf("!!打开文件失败。\r\n");
  136.         }
  137.         /* 不再读写,关闭文件 */
  138.         f_close(&fnew);



  139.       /* 操作完成,停机 */
  140.     printf("》开始扫描文件目录....\r\n");
  141.     strcpy(pathBuff, "");
  142.     scan_files(pathBuff);

  143.     /* 不再使用文件系统,取消挂载文件系统 */
  144.     f_mount(NULL,"0:",1);
程序的运行结果如下:
835485fd07ad04e731.png

成功的创建了三级目录并解析出来。

整个工程打包上传如下:
CH32V103-FATFS-R0.14a-Ver1.1.rar (1.5 MB, 下载次数: 29)


xdqfc 发表于 2020-12-12 10:45 | 显示全部楼层
楼主花了好大的功夫,而且还把文件无私的上传上来,坚决的赞一下。
jinglixixi 发表于 2020-12-12 15:51 | 显示全部楼层
的确有时比较怪异,前一段测试好的,过一段又不行了,真是没法说!
 楼主| xyz549040622 发表于 2020-12-12 22:08 | 显示全部楼层
jinglixixi 发表于 2020-12-12 15:51
的确有时比较怪异,前一段测试好的,过一段又不行了,真是没法说!

是的,搞的人怀疑人生。
 楼主| xyz549040622 发表于 2020-12-12 22:09 | 显示全部楼层
xdqfc 发表于 2020-12-12 10:45
楼主花了好大的功夫,而且还把文件无私的上传上来,坚决的赞一下。

哈哈,测试了好久,确实不容易!
xdqfc 发表于 2020-12-13 09:36 | 显示全部楼层
之前也曾经玩过类似的项目,不过是先弄清楚文件在Flash中的MBR结构后,才下手的,玩了FAT16跟FAT32两种格式,其实,知道文件结构后,玩的就更加爽手了,网上的一些能够下载的库函数,搞的不太明白,所以一直没有用过。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

个人签名:qq群: 嵌入式系统arm初学者 224636155←← +→→点击-->小 i 精品课全集,21ic公开课~~←←→→点击-->小 i 精品课全集,给你全方位的技能策划~~←←

2841

主题

19330

帖子

110

粉丝
快速回复 在线客服 返回列表 返回顶部
个人签名:qq群: 嵌入式系统arm初学者 224636155←← +→→点击-->小 i 精品课全集,21ic公开课~~←←→→点击-->小 i 精品课全集,给你全方位的技能策划~~←←

2841

主题

19330

帖子

110

粉丝
快速回复 在线客服 返回列表 返回顶部