当前位置:   article > 正文

4.5.2 CUBEMX USB之MSC+FATFS+FLASH(内部)_finfo.fattrib 0x16 system~1

finfo.fattrib 0x16 system~1

使用工具型号

  • CUBEMX5.6
  • STM32F103ZET6开发板(正点原子战舰)
  • LINK及其他线束
  • STM32Cube_FW_F1 V1.8.0

1.8.1版本代码只使用DEVICE的时候会出现缺少 发送/接收 函数的实体的错误,1.8.1的包里面的例程也有这个错误,目前不知道如何修改,所以使用了1.8.0

1、CUBEMX初始化

  • 初始化RCC

  • 初始化SYS

  • 初始化USART1

  • 初始化USB

  • 初始化FATFS

  • 初始化USB_DEVICE

2、添加文件

这个是在网上找的一个flash读写文件.

  1. /*
  2. * flash.c
  3. *
  4. * Created: 2018-01-29
  5. * Author: zhanglifu
  6. */
  7. #include "flash.h"
  8. // 不检查的写入
  9. // WriteAddr:起始地址
  10. // pBuffer: 数据指针
  11. // NumToWrite:字节数数
  12. void FlashWriteNoCheck(uint32_t WriteAddr, uint8_t *pBuffer, uint16_t NumToWrite)
  13. {
  14. uint16_t i;
  15. for(i = 0; i < NumToWrite; i += 4)
  16. {
  17. while(HAL_OK != HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, WriteAddr + i, *(uint32_t *)(pBuffer + i)));
  18. }
  19. }
  20. extern void FLASH_PageErase(uint32_t PageAddress);
  21. void FlashWriteBuff(const uint32_t destination_address, uint8_t *const buffer, uint32_t length)
  22. {
  23. uint16_t i;
  24. uint8_t FlashBuff[FMC_SECTOR_SIZE];
  25. uint32_t StartAddress = destination_address - destination_address % FMC_SECTOR_SIZE;
  26. uint16_t Offset = destination_address - StartAddress;
  27. uint8_t *pBuf = buffer;
  28. uint32_t remaindNum = length;
  29. HAL_StatusTypeDef status = HAL_ERROR;
  30. // 地址检查
  31. if((destination_address < FMC_FLASH_BASE) || (destination_address + length >= FMC_FLASH_END) || (length <= 0))
  32. return;
  33. HAL_FLASH_Unlock(); // 解锁
  34. do
  35. {
  36. // 读出一页数据
  37. for(i = 0; i < FMC_SECTOR_SIZE; i += 4)
  38. * (uint32_t *)(FlashBuff + i) = *(uint32_t *)(StartAddress + i);
  39. // 修改要改入的数据
  40. for(i = 0; (i + Offset) < FMC_SECTOR_SIZE && i < remaindNum; i++)
  41. *(FlashBuff + Offset + i) = *(pBuf + i);
  42. // 擦除一ROW数据
  43. FLASH_PageErase(StartAddress);
  44. // HAL库 FLASH_PageErase有BUFF,要加上下面三行代码
  45. while(status != HAL_OK)
  46. status = FLASH_WaitForLastOperation(FLASH_TIMEOUT_VALUE);
  47. CLEAR_BIT(FLASH->CR, FLASH_CR_PER);
  48. // 写入数据
  49. FlashWriteNoCheck(StartAddress, FlashBuff, FMC_SECTOR_SIZE);
  50. // 为下一页做准备
  51. StartAddress += FMC_SECTOR_SIZE;
  52. remaindNum -= i;
  53. pBuf += i;
  54. Offset = 0;
  55. }
  56. while(remaindNum > 0);
  57. HAL_FLASH_Lock(); // 上锁
  58. }
  59. // 从FLASH中读指定长度数据
  60. void FlashReadBuff(const uint32_t source_address, uint8_t *const buffer, uint16_t length)
  61. {
  62. uint16_t i;
  63. uint8_t Offset = 0;
  64. uint32_t StartAddress = source_address;
  65. uint16_t data;
  66. // 地址检测
  67. if(source_address + length > FMC_FLASH_END) return;
  68. // 如果没有对16齐
  69. if(source_address & 1)
  70. {
  71. Offset = 1;
  72. StartAddress = source_address - 1;
  73. }
  74. // flash的操作要求16对齐 最小读写操作16个比特
  75. if(Offset)
  76. {
  77. data = *(uint16_t *)(StartAddress);
  78. buffer[0] = data >> 8;
  79. StartAddress += 2;
  80. }
  81. for(i = 0; i < (length - Offset); i += 2)
  82. {
  83. data = *(uint16_t *)(StartAddress + i);
  84. buffer[i + Offset] = (data & 0xFF);
  85. if((i + Offset) < (length - 1))
  86. buffer[i + Offset + 1] = (data >> 8);
  87. }
  88. }
  1. /*
  2. * flash.h
  3. *
  4. * Created: 2016-04-22
  5. * Author: zhanglifu
  6. */
  7. #ifndef _flash_H_
  8. #define _flash_H_
  9. #include "stm32f1xx_hal.h"
  10. /*********************************************************************/
  11. // 变量定义
  12. /*********************************************************************/
  13. #define STM32_FLASH_BASE 0x08000000 //STM32 FLASH的起始地址
  14. #define FMC_FLASH_BASE 0x08000000 // FLASH的起始地址
  15. #define FMC_FLASH_END 0x08080000 // FLASH的结束地址 64
  16. #define DEVICE_INFO_SIZE 0x0400 // 设备信息大小 1K
  17. #define DEVICE_INFO_ADDRESS (FMC_FLASH_BASE+(100*1024)) // 设备信息起始地址
  18. #define DEVICE_LOG_ADDRESS 0x08008000 // 设备日志起始地址
  19. void FlashReadBuff(const uint32_t source_address, uint8_t *const buffer, uint16_t length);
  20. void FlashWriteBuff(const uint32_t destination_address, uint8_t *const buffer, uint32_t length);
  21. #endif

3、修改usbd_storage_if.c

  • 修改宏定义
  1. #define STORAGE_LUN_NBR 1
  2. #define STORAGE_BLK_NBR ((100*1024)/STORAGE_BLK_SIZ) //0x10000
  3. #define STORAGE_BLK_SIZ (2048/STORAGE_BLOCK_SIZE)
  4. #define STORAGE_BLOCK_SIZE (4)
  • 修改读函数
  1. int8_t STORAGE_Read_FS(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len)
  2. {
  3. /* USER CODE BEGIN 6 */
  4. uint32_t addr = blk_addr * STORAGE_BLK_SIZ;
  5. FlashReadBuff(DEVICE_INFO_ADDRESS + addr, buf, blk_len * STORAGE_BLK_SIZ);
  6. return (USBD_OK);
  7. /* USER CODE END 6 */
  8. }
  • 修改写函数
  1. int8_t STORAGE_Write_FS(uint8_t lun, uint8_t *buf, uint32_t blk_addr, uint16_t blk_len)
  2. {
  3. /* USER CODE BEGIN 7 */
  4. uint32_t addr = blk_addr * STORAGE_BLK_SIZ;
  5. FlashWriteBuff(DEVICE_INFO_ADDRESS + addr, buf, blk_len * STORAGE_BLK_SIZ);
  6. return (USBD_OK);
  7. /* USER CODE END 7 */
  8. }

4、修改user_diskio.c

添加宏定义如下

  1. #define FLASH_SECTOR_SIZE (2048/FLASH_BLOCK_SIZE)
  2. #define FLASH_SECTOR_COUNT ((100*1024)/FLASH_SECTOR_SIZE)//12的单位是MB
  3. #define FLASH_BLOCK_SIZE (4)
  • 修改USER_initializeUSER_status
  1. DSTATUS USER_initialize (
  2. BYTE pdrv /* Physical drive nmuber to identify the drive */
  3. )
  4. {
  5. /* USER CODE BEGIN INIT */
  6. Stat = STA_NOINIT;
  7. Stat &= ~STA_NOINIT;
  8. return Stat ;
  9. /* USER CODE END INIT */
  10. }
  11. DSTATUS USER_status (
  12. BYTE pdrv /* Physical drive number to identify the drive */
  13. )
  14. {
  15. /* USER CODE BEGIN STATUS */
  16. if(pdrv != 0)
  17. Stat = STA_NOINIT;
  18. else
  19. Stat &= ~STA_NOINIT;
  20. return Stat;
  21. /* USER CODE END STATUS */
  22. }
  • 修改读函数
  1. DRESULT USER_read (
  2. BYTE pdrv, /* Physical drive nmuber to identify the drive */
  3. BYTE *buff, /* Data buffer to store read data */
  4. DWORD sector, /* Sector address in LBA */
  5. UINT count /* Number of sectors to read */
  6. )
  7. {
  8. /* USER CODE BEGIN READ */
  9. DRESULT res = RES_ERROR;
  10. if(!count)return res;
  11. uint32_t addr = sector * FLASH_SECTOR_SIZE;
  12. FlashReadBuff(DEVICE_INFO_ADDRESS + addr, buff, count*FLASH_SECTOR_SIZE);
  13. res = RES_OK;
  14. }
  • 修改写函数
  1. DRESULT USER_write (
  2. BYTE pdrv, /* Physical drive nmuber to identify the drive */
  3. const BYTE *buff, /* Data to be written */
  4. DWORD sector, /* Sector address in LBA */
  5. UINT count /* Number of sectors to write */
  6. )
  7. {
  8. /* USER CODE BEGIN WRITE */
  9. DRESULT res = RES_ERROR;
  10. if(!count)return res; //count不能等于0,否则返回参数错误
  11. uint32_t addr = sector * FLASH_SECTOR_SIZE;
  12. FlashWriteBuff(DEVICE_INFO_ADDRESS + addr,(uint8_t *const) buff, count*FLASH_SECTOR_SIZE);
  13. res = RES_OK;
  14. return res;
  15. /* USER CODE HERE */
  16. /* USER CODE END WRITE */
  17. }
  • 修改控制函数
  1. DRESULT USER_ioctl (
  2. BYTE pdrv, /* Physical drive nmuber (0..) */
  3. BYTE cmd, /* Control code */
  4. void *buff /* Buffer to send/receive control data */
  5. )
  6. {
  7. /* USER CODE BEGIN IOCTL */
  8. DRESULT res = RES_ERROR;
  9. switch(cmd)
  10. {
  11. case CTRL_SYNC:
  12. res = RES_OK;
  13. break;
  14. //获取磁盘的扇区大小 只用于f_mkfs
  15. case GET_SECTOR_SIZE:
  16. *(WORD*)buff = FLASH_SECTOR_SIZE;
  17. res = RES_OK;
  18. break;
  19. //获取擦除块的大小 只用于f_mkfs 以扇区为单位
  20. case GET_BLOCK_SIZE:
  21. *(WORD*)buff = FLASH_BLOCK_SIZE;
  22. res = RES_OK;
  23. break;
  24. //获取可利用的扇区大小,MAX_SS>= 1024可用
  25. case GET_SECTOR_COUNT:
  26. *(DWORD*)buff = FLASH_SECTOR_COUNT;
  27. res = RES_OK;
  28. break;
  29. default:
  30. res = RES_PARERR;
  31. break;
  32. }
  33. return res;
  34. /* USER CODE END IOCTL */
  35. }

5、添加测试文件

自己写了一个测试用的文件,不是必需品,只是为了方便测试.

  1. #include "ex_fatfs.h"
  2. #include "fatfs.h"
  3. #include "ff_gen_drv.h"
  4. #include <stdio.h>
  5. #include <string.h>
  6. FRESULT g_res;
  7. FATFS fs;
  8. FIL file;
  9. void fatfs_register()
  10. {
  11. g_res = f_mount(&fs, "0:", 1);
  12. if(g_res == FR_NO_FILESYSTEM)
  13. {
  14. printf("no file systems\r\n");
  15. g_res = f_mkfs("0:", 1, 2048);
  16. if(g_res != FR_OK)
  17. printf("mkfs_failed err code = %d\r\n",g_res);
  18. else
  19. printf("init file systems ok\r\n");
  20. }
  21. else if(g_res != FR_OK)
  22. {
  23. printf("f_mount failed err code = %d\r\n",g_res);
  24. }
  25. else
  26. {
  27. printf("flash have file systems\r\n");
  28. }
  29. }
  30. void fatfs_unregister()
  31. {
  32. g_res = f_mount(NULL, "0:", 1);
  33. if(g_res != FR_OK)
  34. {
  35. printf("file systems unregister failed err code = %d\r\n",g_res);
  36. }
  37. else
  38. {
  39. printf("file systems unregister ok\r\n");
  40. }
  41. }
  42. void fatfs_rw_test()
  43. {
  44. uint8_t w_buf[] = "this is a test txt\n now time is 2020-9-17 22:13\nend";
  45. uint8_t r_buf[200] = {0};
  46. UINT w_buf_len = 0;
  47. UINT r_buf_len = 0;
  48. g_res = f_open(&file, "0:2020.txt", FA_OPEN_ALWAYS | FA_WRITE | FA_READ);
  49. if(g_res != FR_OK)
  50. {
  51. printf("open 2020.txt failed err code = %d\r\n",g_res);
  52. }
  53. else
  54. {
  55. printf("open 2020.txt ok\r\n");
  56. }
  57. g_res = f_write(&file, w_buf, sizeof(w_buf), &w_buf_len);
  58. if(g_res != FR_OK)
  59. {
  60. printf("write 2020.txt failed err code = %d\r\n",g_res);
  61. }
  62. else
  63. {
  64. printf("write 2020.txt ok w_buf_len = %d\r\n", w_buf_len);
  65. f_lseek(&file, 0);
  66. g_res = f_read(&file, r_buf, f_size(&file), &r_buf_len);
  67. if(g_res != FR_OK)
  68. {
  69. printf("read 2020.txt failed g_res = %d\r\n", g_res);
  70. }
  71. else
  72. {
  73. printf("read 2020.txt ok r_buf_len = %d\r\n", r_buf_len);
  74. }
  75. }
  76. f_close(&file);
  77. }
  78. void get_free()
  79. {
  80. FATFS * fs;
  81. DWORD fre_clust, fre_sect, tot_sect;
  82. g_res = f_getfree("0:", &fre_clust, &fs);
  83. if(g_res == FR_OK)
  84. {
  85. tot_sect = (fs-> n_fatent - 2) * fs-> csize;
  86. fre_sect = fre_clust * fs-> csize;
  87. /*打印可用空间(假设每扇区512字节)*/
  88. printf("%lu KB总驱动器空间。\n%lu KB可用\n", tot_sect/2, fre_sect/2);
  89. printf("csize = %d fs-> n_fatent = %d fre_clust = %d \n",fs-> csize,fs->n_fatent,fre_clust);
  90. }
  91. else
  92. {
  93. printf("get_free failed errcode = %d\n",g_res);
  94. }
  95. }
  96. FRESULT scan_files(
  97. char* path /* Start node to be scanned (also used as work area) */
  98. )
  99. {
  100. FRESULT res;
  101. FILINFO fno;
  102. DIR dir;
  103. int i;
  104. char *fn; /* This function assumes non-Unicode configuration */
  105. #if _USE_LFN
  106. static char lfn[_MAX_LFN + 1]; /* Buffer to store the LFN */
  107. fno.lfname = lfn;
  108. fno.lfsize = sizeof lfn;
  109. #endif
  110. res = f_opendir(&dir, path); /* Open the directory */
  111. if(res == FR_OK)
  112. {
  113. i = strlen(path);
  114. for(;;)
  115. {
  116. res = f_readdir(&dir, &fno); /* Read a directory item */
  117. if(res != FR_OK || fno.fname[0] == 0) break; /* Break on error or end of dir */
  118. if(fno.fname[0] == '.') continue; /* Ignore dot entry */
  119. #if _USE_LFN
  120. fn = *fno.lfname ? fno.lfname : fno.fname;
  121. #else
  122. fn = fno.fname;
  123. #endif
  124. if(fno.fattrib & AM_DIR) /* It is a directory */
  125. {
  126. sprintf(&path[i], "/%s", fn);
  127. res = scan_files(path);
  128. path[i] = 0;
  129. if(res != FR_OK) break;
  130. }
  131. else /* It is a file. */
  132. {
  133. printf("%s/%s\n", path, fn);
  134. }
  135. }
  136. f_closedir(&dir);
  137. }
  138. return res;
  139. }
  140. void file_check(void)
  141. {
  142. static FILINFO finfo;
  143. /* 获取文件信息 */
  144. g_res=f_stat("0:2020.txt",&finfo);
  145. if(g_res == FR_OK)
  146. {
  147. printf("2020.txt”文件信息:\n");
  148. printf("》文件大小: %ld(字节)\n", finfo.fsize);
  149. printf("》时间戳: %u/%02u/%02u, %02u:%02u\n",
  150. (finfo.fdate >> 9) + 1980, finfo.fdate >> 5 & 15, finfo.fdate & 31,finfo.ftime >> 11, finfo.ftime >> 5 & 63);
  151. printf("》属性: %c%c%c%c%c\n\n",
  152. (finfo.fattrib & AM_DIR) ? 'D' : '-', // 是一个目录
  153. (finfo.fattrib & AM_RDO) ? 'R' : '-', // 只读文件
  154. (finfo.fattrib & AM_HID) ? 'H' : '-', // 隐藏文件
  155. (finfo.fattrib & AM_SYS) ? 'S' : '-', // 系统文件
  156. (finfo.fattrib & AM_ARC) ? 'A' : '-'); // 档案文件
  157. }
  158. else
  159. {
  160. printf("f_stat failed errcode = %d\n",g_res);
  161. }
  162. }
  163. void set_label()
  164. {
  165. /* Set volume label to the default drive */
  166. g_res = f_setlabel("ZhenRobotic");
  167. if(g_res != FR_OK)
  168. {
  169. printf("SET_LABEL errcode = %d\n",g_res);
  170. }
  171. else
  172. {
  173. printf("SET_LABEL ok \n");
  174. }
  175. }
  1. #ifndef _EX_FATFS_H
  2. #define _EX_FATFS_H
  3. #include "stm32f1xx_hal.h"
  4. #include "fatfs.h"
  5. void fatfs_register(void);
  6. void fatfs_unregister(void);
  7. void fatfs_init_test(void);
  8. void fatfs_rw_test(void);
  9. void get_free(void);
  10. void set_label(void);
  11. FRESULT scan_files (char* path);
  12. void file_check(void);
  13. #endif

6、修改main.c文件

  1. int main(void)
  2. {
  3. /* USER CODE BEGIN 1 */
  4. char file_name[256];
  5. /* USER CODE END 1 */
  6. /* MCU Configuration--------------------------------------------------------*/
  7. /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  8. HAL_Init();
  9. /* USER CODE BEGIN Init */
  10. /* USER CODE END Init */
  11. /* Configure the system clock */
  12. SystemClock_Config();
  13. /* USER CODE BEGIN SysInit */
  14. /* USER CODE END SysInit */
  15. /* Initialize all configured peripherals */
  16. MX_GPIO_Init();
  17. MX_USART1_UART_Init();
  18. MX_USB_DEVICE_Init();
  19. MX_FATFS_Init();
  20. /* USER CODE BEGIN 2 */
  21. fatfs_register();
  22. fatfs_rw_test();
  23. strcpy(file_name, "0:");
  24. scan_files(file_name);
  25. get_free();
  26. file_check();
  27. set_label();
  28. fatfs_unregister();
  29. /* USER CODE END 2 */
  30. /* Infinite loop */
  31. /* USER CODE BEGIN WHILE */
  32. while(1)
  33. {
  34. /* USER CODE END WHILE */
  35. /* USER CODE BEGIN 3 */
  36. }
  37. /* USER CODE END 3 */
  38. }

7、结果

8、上位机添加文件

9、后记

一开始打算将FLASH_BLOCK_SIZESTORAGE_BLOCK_SIZE设置为1,即2048一个扇区(簇),但是这样的话,在进行格式化的时候会死在上图所示的圈红的地方,这个n_vol是挂载的总扇区大小,如果使用2048一个扇区的话,那么至少要有256K空间。在我的使用场景中是不可能有这么大的,后来经过测试,将FLASH_BLOCK_SIZESTORAGE_BLOCK_SIZE修改为4,在60KB的情况下依然可以使用.

这个时候就已经可以做很多事情了,比如将BIN文件放入U盘内,自动读取BIN文件进行固件升级,比如开辟一段专门的空间去进行log记录(这样的话芯片寿命会大幅度降低)。

其实到了这还是有一些疑问,使用文件系统也好,使用USB操作内部FLASH也好,我分配的是100KB,但是在电脑上看到的,使用文件系统读到的都会比100KB小一部分,这部分空间不知道都在哪。

再比如,同样分配100KB空间,扇区大小设置为512,在使用f_mkfs函数的时候,第二个参数使用0的时候,总空间大小只有50KB,使用1的时候有82KB,这两个参数的区别如下

When FDISK format is specified, a primary partition occupies entire space of the physical drive is created and then an FAT volume is created on the partition. When SFD format is specified, the FAT volume starts from the first sector of the physical drive.

总之,环境搭建到现在已经基本满足需求,结束.

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/464043
推荐阅读
相关标签
  

闽ICP备14008679号