文章目录
本文主要介绍cubemx配置fatfs文件系统,以及一些注意事项,细节问题后续补上,需要例程的可以直接跳到第五章。
一、fatfs介绍
略,后续补上。
二、cubemx配置
2.1 配置sdcard
2.1.1 时钟配置
时钟配置成48MHz。
2.1.2 sdmmc配置
选择4位sd模式,4分频即48/4=12MHz为sd卡的运行频率。
2.2 配置fatfs
在配置好sd后,点击fatfs中间件,选择sdcard,在下面的属性里配置中文编码和使能长文件名。
三、编程测试
3.1 准备
//待进行文件操作的数据
FATFS fs; // Work area (file system object) for logical drive
FIL fil; // file objects
uint32_t byteswritten; /* File write counts */
uint32_t bytesread; /* File read counts */
uint8_t wtext[] = "This is STM32 working with FatFs"; /* File write buffer */
uint8_t rtext[100]; /* File read buffers */
char filename[] = "0:/mytest_2021_3_17.txt";
3.2 测试代码
printf("\r\n ****** FatFs Example ******\r\n\r\n");
/*##-1- Register the file system object to the FatFs module ##############*/
//f_mkfs("1:",FM_ANY,0,fatbuf,FF_MAX_SS);
retSD = f_mount(&fs, SDPath, 1);
if(retSD)
{
printf(" mount error : %d \r\n",retSD);
Error_Handler();
}
else
printf(" mount sucess!!! \r\n");
/*##-2- Create and Open new text file objects with write access ######*/
retSD = f_open(&fil, filename, FA_CREATE_NEW | FA_WRITE);
if(retSD)
printf(" open file error : %d\r\n",retSD);
else
printf(" open file sucess!!! \r\n");
/*##-3- Write data to the text files ###############################*/
retSD = f_write(&fil, wtext, sizeof(wtext), (void *)&byteswritten);
if(retSD)
printf(" write file error : %d\r\n",retSD);
else
{
printf(" write file sucess!!! \r\n");
printf(" write Data : %s\r\n",wtext);
}
/*##-4- Close the open text files ################################*/
retSD = f_close(&fil);
if(retSD)
printf(" close error : %d\r\n",retSD);
else
printf(" close sucess!!! \r\n");
/*##-5- Open the text files object with read access ##############*/
retSD = f_open(&fil, filename, FA_READ);
if(retSD)
printf(" open file error : %d\r\n",retSD);
else
printf(" open file sucess!!! \r\n");
/*##-6- Read data from the text files ##########################*/
retSD = f_read(&fil, rtext, sizeof(rtext), (UINT*)&bytesread);
if(retSD)
printf(" read error!!! %d\r\n",retSD);
else
{
printf(" read sucess!!! \r\n");
printf(" read Data : %s\r\n",rtext);
}
/*##-7- Close the open text files ############################*/
retSD = f_close(&fil);
if(retSD)
printf(" close error!!! %d\r\n",retSD);
else
printf(" close sucess!!! \r\n");
3.3 测试结果
由输出的结果可以看出,正确的执行了文件系统的读写和打开关闭操作。
四、注意事项
- 第一次使用的时候出现了错误,原因是没有使能长文件名,从串口输出的调试信息可以看出挂载成功,打开文件f_open失败,错误码是6,表示文件名非法,排查原因为文件名的长度超过8个字节。
五、例程
网络好点就上传。