零、碎碎念和知识储备
0. 说在前面的话
第一次写博客,有写的不好请见谅,欢迎指正。记录一次FATFS文件管理系统的移植过程,以及过程中遇到的问题,以此加深印象,巩固知识。项目是早完成了,但是这期间有些事,还有写博客也非常耗时间,所以文章写的比较晚。此篇文章内容相对累牍连篇,主打一个详细。
写这篇博客的起因是之前做的一个小工程,需要采集声音并且循环播放还要保证无明显失真,那就必须需要用到外部存储器,可惜那个工程时间紧张,移植FATFS失败了,采用的stm32vet6片内flash方案,只能存几秒,失真还严重,心有不甘,暑假相对空闲,就继续尝试移植FATFS文件管理系统。
我在找资料的时候发现似乎没有移植FATFS 0.15版本并且写博客的,原子野火的版本也都有点低,我只找到0.9-0.11版本的,我一想要移我干脆就移植最新版本的,我感觉应该也没多大问题,然后我为期几乎一个星期的移植之旅就开始了(有时候debug改代码改麻了就开摆休息去了,导致花了很久)。
(一)、几个名词释意
1.字符集
OEM: 在ASCII标准之前,因为一个字节有8个比特,而现在只用了7个,于是很多人就想到"对呀,我们可以使用128-255的码字来表示其他东西"。麻烦来了,这么多人同时出现了这样的想法,而且将之付诸实践。于是IBM-PC上多了一个叫OEM字符集的东西。
code pages: 在ASCII标准中,对于低128个码字大家都无异议,差不多就是ASCII了,但对于高128个码字, 根据你所在地的不同,会有不同的处理方式。我们称这样相异的编码系统为码页(code pages)。简体中文使用的是CP936。
Unicode: Unicode:是一个编码方案,Unicode 是为了解决传统的字符编码方案的局限而产生的,它为每种语言中的每个字符设定了统一并且唯一的二进制编码,以满足跨语言、跨平台进行文本转换、处理的要求。Unicode 编码共有三种具体实现,分别为utf-8,utf-16,utf-32,其中utf-8占用一到四个字节,utf-16占用二或四个字节,utf-32占用四个字节。Unicode 码在全球范围的信息交换领域均有广泛的应用。
(二)、SD卡
1. SD卡简介
SD存储卡(Secure Digital Memory Card)是一种基于半导体快闪存储器的新一代高速存储设备。SD存储卡的技术是从MMC卡(MultiMedia Card格式上发展而来,在兼容SD存储卡基础上发展了SDIO(SD Input/ Output)卡,此兼容性包括机械,电子,电力,信号和软件,通常将SD、SDIO卡俗称SD存储卡
一张SD卡包括有存储单元、存储单元接口、电源检测、卡及接口控制器和接口驱动器5 个部分。
存储单元是存储数据部件,存储单元通过存储单元接口与卡控制单元进行数据传输;
电源检测单元保证SD卡工作在合适的电压下,如出现掉电或上状态时,它会使控制单元和存储单元接口复位;
卡及接口控制单元控制SD卡的运行状态,它包括有8个寄存器;
接口驱动器控制 SD 卡引脚的输入输出。
2. SD卡驱动
驱动模式
SD卡有两种驱动模式:SPI模式与SDIO模式。它们所使用的接口信号是不同的。在SPI模式下,只会用到SD卡的4根信号线,即CS、DI、SCLK与DO(分别是SD卡的片选、数据输入、时钟与数据输出)。
传输模式
SD卡共支持三种传输模式:SPI模式(独立序列输入和序列输出),1位SD模式(独立指令和数据通道,独有的传输格式),4位SD模式(使用额外的针脚以及某些重新设置的针脚。支持四位宽的并行传输)。
————————————————
参考链接: STM32使用SPI方式读写SD 卡
(三)、 FATFS文件管理系统
1. FATFS简介
FatFs是面向小型嵌入式系统的一种通用的FAT文件系统。它完全是由ANSI C语言编写并且完全独立于底层的I/O介质。 因此它可以很容易地不加修改地移植到其他的处理器当中,如8051、PIC、AVR、SH、Z80、H8、ARM等。 FatFs支持FAT12、FAT16、FAT32等格式, 所以我们利用前面写好的串行Flash芯片驱动,把FatFs文件系统代码移植到工程之中, 就可以利用文件系统的各种函数,对串行Flash芯片以“文件”格式进行读写操作了。
2. FATFS特性
(1). DOS / Windows兼容的FAT / exFAT文件系统。
(2). 与平台无关,易于移植。
(3). 程序代码和工作区的占用空间非常小。
(4). 支持以下各种配置选项:
1). ANSI / OEM或Unicode中的长文件名。
1). exFAT文件系统,64位LBA和GPT可存储大量数据。
2). RTOS线程支持。
3). 多个卷(物理驱动器和分区,最多10个卷)。
4). 可变扇区大小。
5). 多个代码页,包括DBCS。
6). 只读,可选API,I / O缓冲区等…
3. FATFS提供了以下文件访问函数:
f_open - 打开/创建文件
f_close - 关闭打开的文件
f_read - 从文件中读取数据
f_write - 将数据写入文件
f_lseek - 移动读/写指针,扩展大小
f_truncate - 截断文件大小
f_sync - 刷新缓存的数据
f_forward - 将数据转发到流
f_expand - 为文件分配连续块
f_gets - 读取字符串
f_putc - 写一个字符
f_puts - 编写字符串
f_printf - 编写格式化字符串
f_tell - 获取当前读/写指针
f_eof - 测试文件结尾
f_size - 获取尺寸
f_error - 测试错误
更多详细信息可去官网查看:FatFs官网
SD卡和FATFS介绍参考链接:这位大佬写的无微不至的详细,令人瞠目结舌:
【STM32】使用SDIO进行SD卡读写,包含文件管理FatFs(一)-初步认识SD卡
一、新建工程并且移植必要模块
(一)、硬件材料
起初是准备用stm32c8t6做移植,以后也好移植到大容量的其他单片机,但发现移植起来需要阉割或者使用占用小内存的版本,而且网上的移植大部分也都是zet6起步,综合考虑之下还是选择zet6~
主要是刚好有块正点原子的精英板
有能力可以尝试移植到stm32c8t6,我找资料的时候就看到过CSDN上就有移植到c8t6上的。
参考链接: stm32f103c8t6移植Fatfs文件系统出现的一些问题
stm32单片机Flash和RAM空间大小参考大佬总结:
参考链接: stm32 Keil编译后查看代码/内存占用空间,Flash/RAM占用大小,Code-Data,RO-Data,RW-Data,ZI-Data是什么含义
1. 全部材料
(1).正点原子精英stm32zet6
(2).FATFS 0.15版本
(3).SD卡模块
(4).ST-Link v2(程序下载)
(5).一根USB转接线或者USB转TLL串口模块(串口调试)
(6).杜邦线若干
(7).硬件线路连接
注意说明:
1)由于我精英板比较老,USB-232接口的Mini-B一时间没找到,我就用的uart串口模块连接到单片机引脚,原理都一样,板载有CH340G芯片就可以不用uart串口模块而使用一根USB转接线实现串口打印功能用于调试。
2)如果板载SD卡接口了就不需要SD卡模块了,我的精英板子只有TF卡接口,当然也可使用TF转SD卡套来驱动SD卡
硬件连接如下图:
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
2. 材料详细信息
2.1 正点原子精英板裸板
2.2 FATFS文件管理源码
可以移步官网下载:FatFs官网
选择Download FatFs R0.15(zip)下载 // 图片截取自官网
图 下载位置
我移植时已是最新版,官网也提供了低占用内存的FATFS系统提供8位单片机使用,可以在历史版本里找到或者在图2位置找到并下载。
图1 历史版本
图2 小容量FATFS
2.3 SD卡模块
程序使用的SDIO协议,买的模块是SDIO和SPI都能使用的。改变协议部分相对简单,不再拓展。
2.4 ST-Link
2.5 USB转TTL模块
(二)、新建工程(此部分为基础工程搭建有基础可以不看)
默认已经搭建好Keil 5开发环境的前提下有成功运行过程序,排除一些软件、下载器驱动等问题。
从新建工程开始一步步来,可以说步骤非常详细了
工程文件路径要不要纯英文路径,我试过中英文都能成功运行程序,貌似不影响,以防万一,还是建议放在英文路径下吧
- 新建一个Project(虽然很基础,但是为了从零开始,还是讲一下),给启动文件命名,我这里取FATFS,芯片选择stm32zet6,如图
自动创建的文件如图:
新建CORE,Library,User文件夹用于存放标准库函数、核心启动文件、主函数和中断服务函数。
- 添加核心文件
启动文件的作用:启动文件是任何处理器在上电复位之后最先运行的一段汇编程序。
所有文件都在官方固件包里找得到
2.1 描述文件和启动文件CV到CORE文件夹
文件 | 作用 | 补充 |
---|---|---|
core_cm3.h | 内核寄存器描述 | core_core.c 带有部分内核配置函数 |
stm32f10x.h | 系统寄存器定义申明以及包装内存操作 | 作用和reg51.h文件一样描述stm32有哪些寄存器和对应的地址 |
system_stm32f10x | 主要用于配置系统以及总线时钟 | |
.s文件 | 启动文件 | 具体根据自己的单片机型号选择合适的启动文件 |
2.2 另外的核心文件和mian函数CV到User文件夹
这里我的main.c只是一个电灯程序,在工程中User文件夹下新建一个.c文件并命名为main就好了
文件 | 作用 | 补充 |
---|---|---|
main.c | 主函数 | 最先执行的函数 |
stm32f10x_conf.h | 增加或删除Driver目录下的外设驱动函数库。 | |
stm32f10x_it | 声明、编写中断服务函数 |
这边有大佬表述比较完整: STM32f10X标准固件库各函数作用
2.3 基础文件添加完成,如图所示。
3. 添加文件到工程中,这边有多种方式,我比较喜欢一口气全添对这种方式
3.1 点击更改工程文件的组别名称,并且添加文件到工程中,此处我zet6板选的hd.s的启动文件。
注意:倘若文件显示不齐全,在文件类型选择ALL文件就能看到所有文件了。
3.2 重复次这部分步骤最后得到:
3.3 点击OK,工程文件添加完毕,得到如图所示效果
4. 接着配置Options for Target 包含文件路径
4.1 根据图示步骤,最后得到图片第⑤下面所示的3个文件夹的结果。
注意:后面要加工程文件进来也要在这里吧文件路径包含进来。
4.2 根据下载器自行选择,我此处下拉选择ST-Link
4.3 这步Reset and Run不✔也没事,下载完程序按下复位键,节约点时间就✔了
4.4 编译无错误
4.5 自此,基础工程配置完成。
(三)、移植调试模块
这部分我先是用原子野火的代码,但是发现这个打印利用USART通过printf函数打印还挺有学问,过程中有几个问题都是调用printf函数导致的,而且平时一直就是用的原子或者野火的USART模块函数,但是对于编程原理不求甚解,正好趁这个机会,学习一下,我参考B站江科协的视频和很多博客做了下移植。针对是否使用MicroLIB库都可以实现串口打印。
串口打印相关的问题详细参考我特地另外写的一片文章,解释详细:
printf函数的使用方法总结,注意事项,原理以及拓展,个人学习理解总结
这部分花了很久,自己根据网上资料移植,写了自己学习调试用的USART模块函数,调试完成也都加进了工程里面。
这里经过小修改,工程代码有些细微出入:
1). 把hd.s文件单独放一个工程文件夹。
2). 在System文件加了移植写的USART模块和delay模块函数的简易版本。
操作步骤为:复制粘贴.c、.h文件到System里,然后在keil里把这些文件添加到工程,并且在设置里包含这些文件路径。
3). 在Hardware中加入了一个LED初始化模块,简单点亮板载LED灯。
4). 加了一个README.txt文件。
最终结果如图:
(四)、移植SDIO(SD卡)驱动,移植FATFS系统
这里我是一起移植的,并不是先移植SD卡驱动模块经调试成功后再去移植FATFS文件管理系统。
1. 移植SDIO驱动模块
野火和原子的都能移植,根据SD卡驱动模块里的函数,和在disk.c里的匹配起来就行。
我移植的原子的,因为日期比较新。
后来我又去尝试移植了下野火的,发现程序卡在等待DMA传输完成的循环里了(这个问题网上论坛都能看到有人讨论,但目前网上能找到的解决的方法我尝试了都没成功),最后这个文章已经拖了很久了,也就懒得去继续找原因了。如果后续我解决了会更新在问题解决部分,或者有大佬移植成功解决问题了留言私信告诉我,谢谢了。
我找到的相同问题的论坛: 链接
我这里用的原子的SDIO驱动代码,去原子官方资料下载带FATFS实验,复制粘贴里面的SDIO驱动模块(.c和.h文件),我们只需要这个。
2. 移植FATFS文件管理模块
从FATFS官网下载下来的0.15版本压缩包,解压。
打开source文件夹,分析里面文件的作用。
最上面两个文件:
history.txt就是一些版本更新,修正bug介绍。
readme.txt是介绍一下文件功能,以及注意事项什么的。
名称 | 功能 |
---|---|
ffconf.h | FATFS配置文件 |
ff.h | 应用层头文件 |
ff.c | 应用层源文件 |
diskio.h | 硬件层头文件 |
diskio.c | 底层接口文件(需要用户修改) |
ffunicode.c | 外部功能(比如支持中文等) |
ffsystem.c | 可选O/S相关函数的例子 |
另外一个拓展文件是option
,主要功能添加语言支持库。中文是CC936(CP936)。
option文件是自己添加进来,功能是可选的外部功能(比如支持中文等)根据需要的语言选择支持库。例如中文支持库什cc936.c(文件夹放进工程文件根目录了,但没加进工程中)
interger.h 数据类型定义头文件 在新版的官方文件里删除了
其中,需要修改的文件只有disk.c和ffconf.h文件
2.1 disk.c硬件底层接口文件
主要需要修改的有5个函数和头文件以及宏定义卷标:
- disk_status 函数
- disk_read 函数
- disk_write 函数
- disk_ioctl 函数
- get_fattime 函数
1. disk_status 函数及头文件
#include "ff.h" /* Obtains integer types */
#include "diskio.h" /* Declarations of disk functions */
#include "sdio_sdcard.h" //SDIO驱动模块自行移植
#include <string.h>
#include <stdio.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 */
/* 为每个设备定义一个物理编号 */
#define SD_CARD 0 //SD卡,卷标为0
#define SPI_FLASH 1 //SPI Flash模块,卷标为1 本项目没用到
#define SD_BLOCKSIZE 512
extern SD_CardInfo SDCardInfo; //用于存储卡的信息,DSR的一部分?
/*-----------------------------------------------------------------------*/
/* 获取设备(硬盘)状态函数 */
/*-----------------------------------------------------------------------*/
DSTATUS disk_status (
BYTE pdrv /* Physical drive nmuber to identify the drive */
)
{
DSTATUS status = STA_NOINIT;
switch (pdrv) {
case SD_CARD: /* SD CARD */
/* 设备ID读取结果正确 */
status &= ~STA_NOINIT;
status = RES_OK;
return status;
// case SDIO_FLASH:
/* SPI Flash状态检测:读取SPI Flash 设备ID */
// if(sFLASH_ID == SPI_FLASH_ReadID())
// {
// /* 设备ID读取结果正确 */
// status &= ~STA_NOINIT;
// }
// else
// {
// /* 设备ID读取结果错误 */
// status = STA_NOINIT;;
// }
// break;
default:
status = STA_NOINIT;
}
return STA_NOINIT;
}
2. disk_read 函数
/*-----------------------------------------------------------------------*/
/* 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 */
)
{
DRESULT res;
switch (pdrv) {
case SD_CARD :
// translate the arguments here
res = SD_ReadDisk(buff, sector, count);//很久时间?
// translate the reslut code here
return res;
// case DEV_MMC :
// // translate the arguments here
// result = MMC_disk_read(buff, sector, count);
// // translate the reslut code here
// return res;
// case DEV_USB :
// // translate the arguments here
// result = USB_disk_read(buff, sector, count);
// // translate the reslut code here
// return res;
}
return RES_PARERR;
}
3. disk_write 函数
/*-----------------------------------------------------------------------*/
/* 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 */
)
{
DRESULT res_flash;
switch (pdrv) {
case SD_CARD :
// translate the arguments here
res_flash = SD_WriteDisk((u8*)buff, sector, count);
// translate the reslut code here
return res_flash;
// case DEV_MMC :
// // translate the arguments here
// result = MMC_disk_write(buff, sector, count);
// // translate the reslut code here
// return res;
// case DEV_USB :
// // translate the arguments here
// result = USB_disk_write(buff, sector, count);
// // translate the reslut code here
// return res;
}
return RES_PARERR;
}
#endif
4. disk_ioctl 函数
/*-----------------------------------------------------------------------*/
/* Miscellaneous Functions */
/*-----------------------------------------------------------------------*/
DRESULT disk_ioctl (
BYTE pdrv, /* Physical drive nmuber (0..) */
BYTE cmd, /* Control code */
void *buff /* Buffer to send/receive control data */
)
{
DRESULT status = RES_PARERR;
switch (pdrv) {
case SD_CARD: /* SD CARD */
switch (cmd)
{
// Get R/W sector size (WORD)
case GET_SECTOR_SIZE :
*(WORD * )buff = SD_BLOCKSIZE;
break;
// Get erase block size in unit of sector (DWORD)
case GET_BLOCK_SIZE :
*(DWORD * )buff = 1;
break;
case GET_SECTOR_COUNT:
*(DWORD * )buff = SDCardInfo.CardCapacity/SDCardInfo.CardBlockSize;
break;
case CTRL_SYNC :
break;
}
status = RES_OK;
break;
case SPI_FLASH:
break;
default:
status = RES_PARERR;
}
return status;
}
5. get_fattime 函数
__weak DWORD get_fattime(void) {
/* 返回当前时间戳 */
return ((DWORD)(2015 - 1980) << 25) /* Year 2015 */
| ((DWORD)1 << 21) /* Month 1 */
| ((DWORD)1 << 16) /* Mday 1 */
| ((DWORD)0 << 11) /* Hour 0 */
| ((DWORD)0 << 5) /* Min 0 */
| ((DWORD)0 >> 1); /* Sec 0 */
}
2.2 ffconf.h 文件
ffconf.h 文件
/*---------------------------------------------------------------------------/
/ Configurations of FatFs Module
/---------------------------------------------------------------------------*/
#define FFCONF_DEF 80286 /* 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 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 //´ËÑ¡ÏîÉèÖÃÊÇ·ñÆôÓÃf_mkfs()º¯Êý
/* 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 1
#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/2
/ makes 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 936 //´ËÑ¡ÏîÉèÖÃʹÓÃÖ¸¶¨OEM´úÂëÒ³
/* 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 2 //´ËÑ¡ÏîÇл»¶Ô³¤ÎļþÃûµÄÖ§³Ö
#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 //´ËÑ¡ÏîÉèÖÃÊÇ·ñÆôÓÃunicode×Ö·û±àÂë
/* 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 0
/* 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 1 //ÉèÖÃÒªÆôÓõľí(Âß¼Çý¶¯Æ÷)µÄÊýÁ¿(·¶Î§1-10)
/* 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 is needed 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()
/ function will be available. */
#define FF_MIN_SS 512
#define FF_MAX_SS 2048 //Õâ×éÑ¡ÏîÉèÖÃÖ§³ÖµÄÉÈÇø´óС·¶Î§
/* 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 1
#define FF_NORTC_MON 1
#define FF_NORTC_MDAY 1
#define FF_NORTC_YEAR 2022
/* The option FF_FS_NORTC switches timestamp feature. If the system does not have
/ an RTC or valid timestamp is not needed, set FF_FS_NORTC = 1 to disable the
/ timestamp feature. 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 the 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. */
#define FF_FS_REENTRANT 0
#define FF_FS_TIMEOUT 1000
/* 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 featuer.
/
/ 0: Disable re-entrancy. FF_FS_TIMEOUT have no effect.
/ 1: Enable re-entrancy. Also user provided synchronization handlers,
/ ff_mutex_create(), ff_mutex_delete(), ff_mutex_take() and ff_mutex_give()
/ function, must be added to the project. Samples are available in ffsystem.c.
/
/ The FF_FS_TIMEOUT defines timeout period in unit of O/S time tick.
*/
/*--- End of configuration options ---*/
移植0.15版本遇到的问题。
起初网上一时找不到0.15的版本的移植,0.15版本的函数和0.14版本有点差别,和更早版本函数的参数不一样,不能无脑cv大法。导致这边也花了一些时间。这边建议看野火的的官方实验资料,里面是更新到0.15版本的说明了,但是实验源码还是老版本,需要自己根据资料移植,我main函数里的已经是根据0.15版本修改好的了,复制粘贴就好。
链接: FATFS R0.14b最新版移植到STM32
链接: FATFS文件系统常用指令
二、主函数及调试验证
#include "stm32f10x.h" // Device header
#include "ff.h"
#include "sdio_sdcard.h"
#include <stdio.h>
#include "usart.h"
//#include "oled.h"
#include "delay.h"
FATFS fs; /* FatFs文件系统对象 */
FIL fnew; /* 文件对象 */
FRESULT res_flash; /* 为SD卡磁盘注册工作区定义,文件操作结果显??/
UINT fnum; /* 文件成功读写数量 */
//BYTE work[1024]={0}; /* 工作缓冲区*/
BYTE ReadBuffer[1024]={0}; /* 读缓冲区 */
//BYTE WriteBuffer[] ="";
BYTE WriteBuffer[] = "hello! 你好!"; /* 写缓冲区 */
//通过串口打印SD卡相关信息
void show_sdcard_info(void)
{
switch(SDCardInfo.CardType)
{
case SDIO_STD_CAPACITY_SD_CARD_V1_1:printf("Card Type:SDSC V1.1\r\n");break;
case SDIO_STD_CAPACITY_SD_CARD_V2_0:printf("Card Type:SDSC V2.0\r\n");break;
case SDIO_HIGH_CAPACITY_SD_CARD:printf("Card Type:SDHC V2.0\r\n");break;
case SDIO_MULTIMEDIA_CARD:printf("Card Type:MMC Card\r\n");break;
}
printf("\r\nSD卡信息\r\n");
printf("Card ManufacturerID:%d\r\n",SDCardInfo.SD_cid.ManufacturerID); //制造商ID
printf("Card RCA:%d\r\n",SDCardInfo.RCA); //卡相对地址
printf("Card Capacity:%d MB\r\n",(u32)(SDCardInfo.CardCapacity>>20)); //显示容量
printf("Card BlockSize:%d\r\n\r\n",SDCardInfo.CardBlockSize); //显示块大小
}
int main(void)
{
uart_init(115200);
printf("外设初始化开始\r\n!");
delay_init();
// OLED_display_frame(); //显示固定常亮字符
printf("外设初始化成功\r\n!");
printf("\r\n*********** 这是一个 SD_CARD 文件系统实验 ***********\r\n");
//在外部SPI Flash挂载文件系统,文件系统挂载时会对SPI设备初始化
//初始化函数调用流程如下
//f_mount()->find_volume()->disk_initialize->SPI_FLASH_Init()
res_flash = f_mount(&fs,"0:",1);
/*----------------------- 格式化测试 -----------------*/
/* 如果没有文件系统就格式化创建创建文件系统 */
if(res_flash == FR_NO_FILESYSTEM)
{
printf("》SD_CARD还没有文件系统,即将进行格式化...\r\n");
/* 格式化 */
res_flash = f_mkfs ( "0:",NULL,ReadBuffer, sizeof(ReadBuffer));
if(res_flash == FR_OK)
{
printf("》SD_CARD已成功格式化文件系统。\r\n");
/* 格式化后,先取消挂载 */
res_flash = f_mount(NULL,"0:",1);
/* 重新挂载 */
res_flash = f_mount(&fs,"0:",1);
}
else
{
// LED_RED;
printf("《《格式化失败。》》\r\n");
while(1);
}
}
else if(res_flash!=FR_OK)
{
printf("!!外部Flash挂载文件系统失败。(%d)\r\n",res_flash);
printf("!!可能原因:SDIO Flash初始化不成功。\r\n");
while(1);
}
else
{
printf("》文件系统挂载成功,可以进行读写测试\r\n");
}
show_sdcard_info();//显示卡信息
/*----------------------- 文件系统测试:写测试 -------------------*/
/* 打开文件,每次都以新建的形式打开,属性为可写 */
printf("\r\n*********** 即将进行文件写入测试。。。 ***********\r\n");
res_flash = f_open(&fnew, "0:FatFs读写测试文件.txt",FA_CREATE_ALWAYS | FA_WRITE );
if ( res_flash == FR_OK )
{
printf("》打开/创建FatFs读写测试文件.txt文件成功,向文件写入数据。\r\n");
/* 将指定存储区内容写入到文件内 */
res_flash=f_write(&fnew,WriteBuffer,sizeof(WriteBuffer),&fnum);
if(res_flash==FR_OK)
{
printf("》文件写入成功,写入字节数据:%d\n",fnum);
printf("》向文件写入的数据为:\r\n%s\r\n",WriteBuffer);
}
else
{
printf("!!文件写入失败:(%d)\n",res_flash);
}
/* 不再读写,关闭文件 */
f_close(&fnew);
}
else
{
// LED_RED;
printf("!!打开/创建文件失败。\r\n");
}
/*------------------- 文件系统测试:读测试 --------------------------*/
printf("\r\n*********** 即将进行文件读取测试。。。 ***********\r\n");
res_flash = f_open(&fnew, "0:FatFs读写测试文件.txt",FA_OPEN_EXISTING | FA_READ);
if(res_flash == FR_OK)
{
// LED_GREEN;
printf("》打开文件成功。\r\n");
res_flash = f_read(&fnew, ReadBuffer, sizeof(ReadBuffer), &fnum);
if(res_flash==FR_OK)
{
printf("》文件读取成功,读到字节数据:%d\r\n",fnum);
printf("》读取得的文件数据为:\r\n%s \r\n", ReadBuffer);
}
else
{
printf("!!文件读取失败:(%d)\n",res_flash);
}
}
else
{
// LED_RED;
printf("!!打开文件失败。\r\n");
}
/* 不再读写,关闭文件 */
f_close(&fnew);
/* 不再使用文件系统,取消挂载文件系统 */
f_mount(NULL,"0:",1);
/* 操作完成,停机 */
while(1)
{
}
}
工程文件图示:
测试效果图:
1.输入数据到写入缓存区:
2.成功挂载系统初始化,并且读写数据:
3.显示SD卡信息:
4.读卡器读取SD卡数据文件:
5.试一下改变写缓存区数据:
)
)
6.依然没问题,结束。
三、过程中遇到的问题
当然出现问题只是我解决的方案,还是会有其他可能的原因导致的问题,如果还是无法解决,还需要找其他大佬博客的方法都去试试。
问题1:移植某版本的正点或野火的uart.c模块,出现_sys错误。
图1
FILE __stdout;
//定义_sys_exit()以避免使用半主机模式
_sys_exit(int x)
{
x = x;
}
图2
这个问题在某些版本的uart模块情况下会发生
定义 _sys_exit(int x) 以避免使用半主机模式,函数没有返回类型,假定其返回类型为int,可以写为 void _sys_exit(int x) ,否则编译器会默认为返回int类型,故会出现上述警告。
解决办法:
将_sys_exit(int x) 写成void _sys_exit(int x)
参考博客/文章链接:
链接: …\SYSTEM\usart\usart.c(48): error: #260-D: explicit type is missing (“int” assumed)
问题2:keil不能设置断点的问题
Debug->Settings里的Cache Options 没有进行勾选,而Download Options 进行了勾选或者全都勾选了,我是全都勾选出现的问题。
解决方法:
如图Cache Code和Download Options部分就是正确设置。
参考博客/文章链接:
链接: keil不能设置断点的问题解决
问题3:程序卡死,没进入到主函数
程序直接卡死没进入到主函数,main.c里找不到蓝箭头。然后在startup_stm32f10x_hd.s中找到了蓝色箭头。
解决办法:
这里消耗了大量时间,我还老以为DMA和sdio驱动哪里中断函数没设置好,检查了很久。
1.尽可能使用独立电源或者充电器给开发板供电,而不是使用了ST-Link的供电线就高枕无忧了
我就是检查了一堆问题好了好几天之后,发现用充电器给开发板供电就解决了
2.printf等打印函数使用指南参考链接: 【stm32串口打印】printf函数的使用方法,注意事项,原理以及拓展,个人学习理解总结
参考博客/文章链接:
链接: 记一次 Keil 硬件调试卡死(不进 main、不显示黄色箭头)
链接: KEIL debug无法进入main函数 或 debug卡死的原因总结_keil 在调试的时候不能开始_sarsscofy的博客-CSDN博客
链接: STM32程序进不了main函数奇葩现象—你不知道的原因
链接: keil调试中程序停在 SystemInit 处
printf等打印函数个人理解整理总结的参考链接: 【stm32串口打印】printf函数的使用方法,注意事项,原理以及拓展,个人学习理解总结
问题4:程序加入主函数但是死机
解决办法:
没遇到过,可参考链接文章
参考博客/文章链接:
链接: stm32死机问题的处理
问题5:挂载文件系统失败,SDIO卡驱动模块初始化失败
图中打印的SPI Flash并不是SPI协议,只是打印示意printf函数里面没改,我用的是SDIO协议
解决办法:
由于我是做完项目才写的博客,具体错误原因混淆了,但是这几类问题具基本可以通过下面的方式排除错误。
1.首先严格检查接线(我就是SDIO线接错了导致此问题)
2.同样检查SDIO接线,SD卡硬件模块供电,没达到指定电压可能无法达到通信要求的启动电平。
3.根据printf函数里()返回的数字,找到对应错误代码定义,针对排除,这里太多错误代码了,需要耐心排除,这里就不适合展开说了。
4.如果返回值还是太模糊不能清楚定位,就需要debug观察返回值在具体哪一步变化以及if、else的判断条件满足条件。
5.还有很可能的原因是disk.c的接口代码没有写好,这个问题在我没有发现有人移植0.15版本,并且发文章的情况下找资料看代码,还是很费精力的。现在,按理说复制我写好的代码过去应该就可以了。
参考博客/文章链接:
参考链接: 关于SD卡挂载失败问题的解决方法
问题6:txt文件名报错
这个因为我配置好了ffconf文件,所以没遇到过。
原因之一是因为文件系统未支持长文件名。
解决方法:
1.换英文文件名
2.在ffconf.h文件里修改以支持长文件名。
参考博客/文章链接:
链接: 配置 FATFS 支持长文件名
问题7:0.15版本函数参数结构改变导致的错误
在0.15版本中f_mount和f_mkfs函数参数结构发生变化了。
有c和数据结构基础不难理解,或者直接复制我main函数里的用法。
解决方法:
f_mount 函数
/* 申请注册磁盘 */
res_flash = f_mount(&fs,"0:",1);
f_mkfs 函数
/* 格式化 */
res_flash = f_mkfs ( "0:",NULL,ReadBuffer, sizeof(ReadBuffer));
具体在ff15文件里面用编译器定位函数位置然后查看各参数英文原文介绍。
参考博客/文章链接:
主要框架参考链接: 野火官网SD卡+FATFS实验
问题N(未解决):移植官方例程和野火的FATFS代码在等待DMA传输完毕中循环跳不出来
如下三张图,程序在这三个函数内循环
串口助手调试结果:
初始化之后就卡在while循环里了。
解决方法:
这个问题网上论坛都能看到有人讨论,但目前网上能找到的解决的方法我尝试了都没能成功,已经成功移植原子的了,迫于时间因素,放弃官方和野火的SDIO驱动代码移植尝试,希望有人解决了可以私聊留言我,感谢。
参考博客/文章链接:
找到的相同问题论坛: SD_WaitReadOperation()或者SD_WaitWriteOperation()函数死循环
链接: 求教,SD卡中擦除函数中Status=SD_WaitReadOperation();为什么会
四、总结(没什么好看的)
耗时之久,debug之麻烦令人发指,有时候真的就是一杯茶一包烟(不过诚然我不抽烟),一个bug改一天。
收获还是有的,慢慢养成写博客习惯,以后就有固定模板了。不论是分享还是方便自己以后回来看,所以我留了大量的链接,方便跳转学习,构建起一个知识小网络。不过确实还是有很多潦草的地方,因为太花时间了,可能自己在非常混乱的精神状态下debug改好了代码,但是你可能说不通,或者要讲明白需要大量精力时间自己也要去深入学习,看懂代码,理解原理解释清楚而不是只会移植修改修改代码。这样工作量就太大了,这实验和两三个小实验到我写到总结,前前后后花了3个星期了。。。
之后也会偶尔补充解决问题的。
此外,有其他问题也欢迎。
其他参考博客/文章链接:
链接: KEIL5中Debug调试_keil5debug调试_小阳先生的宝库的博客-CSDN博客解决Keil调试模式下无法设置断点的问题_keil调试打不了断点_Crystal记忆的博客-CSDN博客
链接: KEIL debug无法进入main函数 或 debug卡死的原因总结_keil 在调试的时候不能开始_sarsscofy的博客-CSDN博客
主要框架参考链接:
【STM32】使用SDIO进行SD卡读写,包含文件管理FatFs(一)-初步认识SD卡
主要框架参考链接: 野火官网SD卡+FATFS实验
主要框架参考链接: 基于STM32完成FATFS文件系统移植运用-这是完全免费开源的FAT文件系统
主要框架参考链接: STM32F103-FATFS 文件系统移植
主要框架参考链接: Stm32文件系统FATFS(开始于2021-09-09)
主要框架参考链接: 第37章 基于SD卡的FatFs文件系统—零死角玩转STM32-F429系列
链接: STM32利用FATFS文件系统给SD卡读写数据
链接: STM32使用SPI方式读写SD 卡
链接: STM32的简单的SD卡读写
链接: STM32+SD卡 使用问题记录(一)
内存:
链接: 外部存储芯片(详细说明)
链接: STM32F103C8T6的内部Flash以及实例
知乎链接: SDIO协议浅析