先用STM32CubeMX生成程式碼
需要:
1.RCC
2.SYS
3.SDIO
4.USART1(偵錯用)
5.FATFS(SD Card)
需要設定中斷:無
設定 SDIOCLK clock divide factor (一般設定4-8)
這是對應的標準庫sd卡的設定
設定非同步通訊模式
生成程式碼
需要加上stdio.h檔案
#include "stdio.h"
int fputc(int ch, FILE *f)
{
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xffff);
return ch;
}
/**
* 函數功能: 重定向c庫函數getchar,scanf到DEBUG_USARTx
* 輸入參數: 無
* 返 回 值: 無
* 說 明:無
*/
int fgetc(FILE * f)
{
uint8_t ch = 0;
HAL_UART_Receive(&huart1,&ch, 1, 0xffff);
return ch;
}
2.在main.c裡寫使用者程式
FATFS fs; /* FatFs檔案系統物件 */
FIL file; /* 檔案物件 */
BYTE ReadBuffer[255]={0}; /*讀緩衝區*/
BYTE WriteBuffer[20]="11111"; /*寫緩衝區*/
首先要瞭解幾個函數
f_mount 掛載檔案系統
f_open 開啓檔案 檢視f_open函數發現fp->fptr = 0;fp->dsect = 0;呼叫後每次開啓檔案會將指針清零,所以每次都從頭寫。
f_lseek 此函數用於檔案指針的移動,共有兩個參數,第一個參數爲檔案物件,第二個參數爲移動的位元組數,注意第二個參數是相對於檔案的開始.
f_close 關閉檔案
上程式碼
void SD_Write_Test(void)
{
int res = 0;
UINT write_num = 0;
res = f_mount(&fs,"0:",1); //掛載檔案系統
if(res != FR_OK)
{
printf("f_mount is error,error code is ;%d\r\n",res);
}
else
{
printf("f_mount is successed! test open file\r\n");
res = f_open(&file,"test.txt",FA_READ|FA_WRITE|FA_OPEN_ALWAYS);
int FileSize = f_size(&file);
if(res != FR_OK)
{
printf("f_open is error,error code is ;%d\r\n",res);
}
else
{
if(FileSize>3) //就算檔案裡沒有數據,也算是有一個位元組,所以要判斷一下,防止檔案爲空時移動
{
res=f_lseek(&file,FileSize);
if(res != FR_OK)
{
printf("f_lseek is error,error code is ;%d\r\n",res);
}
}
res = f_write(&file,WriteBuffer,sizeof(WriteBuffer),&write_num);
res = f_write(&file,"\r\n",sizeof("\r\n"),&write_num);
if(res != FR_OK)
{
printf("f_write is error,error code is ;%d\r\n",res);
}
else{
printf("TRUE write word to file size is :%d\r\n",write_num);
}
res = f_close(&file);
if(res != FR_OK)
{
printf("f_close is error,error code is ;%d\r\n",res);
}
else
{
printf("f_close is successed!\r\n");
}
}
}
}
void SD_read_Test(void)
{
int res = 0;
UINT write_num = 0;
res = f_mount(&fs,"0:",1); //掛載檔案系統
res = f_open(&file,"test.txt",FA_READ|FA_WRITE|FA_OPEN_ALWAYS);
res = f_read(&file,ReadBuffer,100,&write_num);
if(res != FR_OK)
{
printf("f_read is error,error code is ;%d\r\n",res);
}
else{
printf("TRUE read word to file size is :%d\r\n %s\r\n",write_num,ReadBuffer);
}
res = f_close(&file);
}
別忘了在main函數之前定義一下。
![在這裏插入圖片描述](https://img-blog.csdnimg.cn/20200808212616699.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2Jvcmxp,size_16,color_FFFFFF,t_70
可以和模擬U盤一起使用,當USB DEVICE與電腦連線時,停止向sd卡寫數據。