链接:https://pan.baidu.com/s/1MFVI8M022kbmuOlGbAl6aw 提取码:xhc1
下载源程序
下载完成后打开
修改此处,否则会有乱码
主函数
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_SPI1_Init();
MX_FATFS_Init();
MX_USART1_UART_Init();
HAL_UART_Receive_IT(&huart1,&aRxBuffer1,1); //enable uart
printf(" mian rn");
Get_SDCard_Capacity(); //得到使用内存并选择格式化
while (1)
{
WritetoSD(WriteBuffer,sizeof(WriteBuffer));
HAL_Delay(500);
WriteBuffer[0] = WriteBuffer[0] +0;
WriteBuffer[1] = WriteBuffer[1] +1;
write_cnt ++;
while(write_cnt > 10)
{
printf(" while rn");
HAL_Delay(500);
}
}
}
SD卡写入函数
void WritetoSD(BYTE write_buff[],uint8_t bufSize)
{
FATFS fs;
FIL file;
uint8_t res=0;
UINT Bw;
res = SD_init(); //SD卡初始化
if(res == 1)
{
printf("SD卡初始化失败! rn");
}
else
{
printf("SD卡初始化成功! rn");
}
res=f_mount(&fs,"0:",1); //挂载
// if(test_sd == 0) //用于测试格式化
if(res == FR_NO_FILESYSTEM) //没有文件系统,格式化
{
// test_sd =1; //用于测试格式化
printf("没有文件系统! rn");
res = f_mkfs("", 0, 0); //格式化sd卡
if(res == FR_OK)
{
printf("格式化成功! rn");
res = f_mount(NULL,"0:",1); //格式化后先取消挂载
res = f_mount(&fs,"0:",1); //重新挂载
if(res == FR_OK)
{
printf("SD卡已经成功挂载,可以进进行文件写入测试!rn");
}
}
else
{
printf("格式化失败! rn");
}
}
else if(res == FR_OK)
{
printf("挂载成功! rn");
}
else
{
printf("挂载失败! rn");
}
res = f_open(&file,SD_FileName,FA_OPEN_ALWAYS |FA_WRITE);
if((res & FR_DENIED) == FR_DENIED)
{
printf("卡存储已满,写入失败!rn");
}
f_lseek(&file, f_size(&file));//确保写词写入不会覆盖之前的数据
if(res == FR_OK)
{
printf("打开成功/创建文件成功! rn");
res = f_write(&file,write_buff,bufSize,&Bw); //写数据到SD卡
if(res == FR_OK)
{
printf("文件写入成功! rn");
}
else
{
printf("文件写入失败! rn");
}
}
else
{
printf("打开文件失败!rn");
}
f_close(&file); //关闭文件
f_mount(NULL,"0:",1); //取消挂载
}
接线
修改输入
输出三行



