CUBE+SD卡讀寫大量數據/存TXT文件+SPI通信+電路圖+源程序+軟件解決熱插拔

電路圖如下(注,通過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);這句解決連續存儲

這個論壇有介紹

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章