电路图如下(注,通过SPI和SD卡通信;没有在硬件上通过额外引脚判断SD卡是否存在,通过程序检测解决SD热插拔问题):
CUBE配置:
SPI,SD卡如何进SPI模式
fatfs,先在cube的Pinout下选上FATFS下的User-defined,fatfs系统指令详解
程序解决热插拔,具体见源代码
uint8_t SD_Init(void)
{
/* Mount SD Card */
fres = f_mount(&fs, "", 1);
if(fres != FR_OK)
{
SD_disk_initialize(fs.drv);
return 0;
}
/* Open file to write */
if(f_open(&fil, "pm_data.txt", FA_OPEN_ALWAYS | FA_READ | FA_WRITE) != FR_OK)
return 0;
/* Check free space */
if(f_getfree("", &fre_clust, &pfs) != FR_OK)
return 0;
else
{
total = (uint32_t)((pfs->n_fatent - 2) * pfs->csize * 0.5); //all total is ECF20
free = (uint32_t)(fre_clust * pfs->csize * 0.5); //all free is ECEC0
sd_status = free * 1000 / (total / 10);//0.01
sd_status = 10000 - sd_status ;
tx_screen[4] = 0x11; tx_screen[5] = 0x10; tx_screen[6] = (sd_status >> 8) & 0xff; tx_screen[7] = sd_status & 0xff; //int sd ->0.01
HAL_UART_Transmit(&huart5, (uint8_t *)tx_screen, sizeof(tx_screen),0xFFFF);//tx
}
/* Free space is less than 1kb */
// if(free < 1)
// return 0;
/* Writing text */
if(free > 100)//100B
{
f_lseek(&fil,fil.fsize);//move the guide
f_puts("The pm is:", &fil); //970000/16=60625,one min/time 60625min = 1010hour = 42days
// f_printf(&fil, "%ld\n", fil.fsize);
f_printf(&fil, "%ld\n", rx_slave[1]*256 + rx_slave[2]);
// f_printf(&fil, "%ld\n", sd_status);
}
/* Close file */
if(f_close(&fil) != FR_OK)
return 0;
/* Open file to read */
// if(f_open(&fil, "pm_data.txt", FA_READ) != FR_OK)
// return 0;
//
// while(f_gets(buffer, sizeof(buffer), &fil))
// {
// printf("%s", buffer);
// }
/* Close file */
// if(f_close(&fil) != FR_OK)
// return 0;
/* Unmount SDCARD */
if(f_mount(NULL, "", 1) != FR_OK)
return 0;
return 1;
}
注意事项:不同类型CMD指令不同,本SD卡指令前都加0X40,如下
#define CMD0 (0x40+0) /* GO_IDLE_STATE */
#define CMD1 (0x40+1) /* SEND_OP_COND */
#define CMD8 (0x40+8) /* SEND_IF_COND */
#define CMD9 (0x40+9) /* SEND_CSD */
#define CMD10 (0x40+10) /* SEND_CID */
#define CMD12 (0x40+12) /* STOP_TRANSMISSION */
#define CMD16 (0x40+16) /* SET_BLOCKLEN */
#define CMD17 (0x40+17) /* READ_SINGLE_BLOCK */
#define CMD18 (0x40+18) /* READ_MULTIPLE_BLOCK */
#define CMD23 (0x40+23) /* SET_BLOCK_COUNT */
#define CMD24 (0x40+24) /* WRITE_BLOCK */
#define CMD25 (0x40+25) /* WRITE_MULTIPLE_BLOCK */
#define CMD41 (0x40+41) /* SEND_OP_COND (ACMD) */
#define CMD55 (0x40+55) /* APP_CMD */
#define CMD58 (0x40+58) /* READ_OCR */
写入文件后,必须关闭文件,才能成功
先确保SPI和SD卡通信上,再弄FATFS系统
如果挂载用f_mount(&fs, "", 0);就是稍后挂载,这样,不管有没有SD卡都会显示挂载成功;如果用f_mount(&fs, "", 1);就是立即挂载,这样,没有SD卡就不成功,同原理解决热插拔
按照文件现有大小移动指针,f_lseek(filescr1,filescr1->fptr+filescr1->fsize);这句解决连续存储
这个论坛有介绍