STM32 Configure SPI Read-Write SD Card in FATFS Mode with cube

Posted by chingwaah on Wed, 22 Dec 2021 22:16:59 +0100

Requirements: Master the principle of SD card protocol, complete the data reading of SD card with STM32F103 (FAT file mode)

1. SD card and FATS

1. SD card

(1) Introduction
SD card (Secure Digital Memory Card) is very common in our life. Controllers usually have two communication interfaces to read and write SD card, one is SPI interface, the other is SDIO interface. The full name of SDIO is a secure digital input/output interface. Multimedia cards (MMC), SD cards, SD I/O cards all have SDIO interfaces. SD I/O card itself is not a storage card, it refers to a peripheral using SDIO transport protocol. For example, Wi-Fi Card, which mainly provides Wi-Fi functionality, some Wi-Fi modules use serial or SPI interface for communication, but Wi-Fi SDIO Card uses SDIO interface for communication.
(2) Operation mode
SD card operation mode: SD card mode (SDIO), SPI mode (SD mode by default).
The signal lines of SD card mode are CLK, CMD, DAT0-DAT3, 6 lines.
The signal lines in SPI mode are CS, CLK, MISO (DATAOUT), MOSI(DATAIN),4 lines.

CLK Clock Synchronization Line
CMD command signal line, commands from host and responses from slave to commands are all transmitted through this line
DAT[3:0] represents four data lines from which both host and slave data are transmitted

(3) Physical structure
An SD card consists of a storage unit, a storage unit interface, power detection, a card, an interface controller and an interface driver. The storage unit is the storage data unit, which transmits data with the card control unit through the storage unit interface. The power detection unit guarantees that the SD card works at an appropriate voltage, and resets the interface between the control unit and the storage unit in case of power failure or power-up. Five parts of the card and interface control unit control the operation status of the SD card, which includes eight registers. The interface driver controls the input and output of the pin of the SD card.

  • The SD card function block diagram is as follows

2. FATFS File System

FATFS is a general FAT file system for small embedded systems. It is written by ANSI C language and is completely independent of the underlying I/O media. Therefore, it can be easily ported to other processors without modification, and the formatted SD card files can be read and written using various functions of the file system.

2. Engineering Realization

Due to limited capacity, this time the main work is to use the completed projects directly, and make some modifications on this basis. For details on the construction of the project, you can see this article:
https://blog.csdn.net/qq_39758638/article/details/103573843
Place the download connection for the project here:
https://pan.baidu.com/s/1izzu14Zy2myHm2ZI4NFSGg
Extraction Code: t11v

1. Compile and run

Open the MDK-ARM folder in the downloaded file, where you can find the project file, and open it with keil

Compile run, no errors found

2. Wiring

Connect as shown below

SD cardSTM32
CSPA4
SCKPA5
MISOPA6
MISIPA7
VCC5V
GUNGUN


Note:

  • The power supply needs to be 5V, the initial set power supply is 3.3V, but the experiment is unsuccessful, change to 5V to run successfully, so there may be insufficient power supply of 3.3V
  • The DuPont Line is as short as possible and preferably as tight as possible, because these details largely determine your success.

3. Initialization file mode

Before you start burning officially, to initialize the SD card, the file system is FAT32, then click Start to finish

A pop-up window appears and click OK

Successfully formatted

4. Burning

Open the mcuisp file and burn it in the following order

  • Search Serial Port
  • Select the hex file you just generated
  • Read device information
  • Start programming

The text on the right side indicates that burning was successful

5. Experimental results

Open Serial Debugging Assistant and click Open Serial Port
If the right side has always been the word mian, try pressing the connection with your hand
Found that the serial port received information, showing that the SD card was initialized successfully, mounted successfully, opened successfully, and created successfully

Reading the SD card with a card reader, we found a file HELLO in the folder. TXT

When I opened the file, I found a string of characters showing, but with garbage

To resolve this error, the code was modified to include main. Comment out these two lines in C

Execute the steps more than once again and find no errors

3. Code Analysis

Principal function

int main(void)
{
  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */
  

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_SPI1_Init();
  MX_FATFS_Init();
  MX_USART1_UART_Init();
  /* USER CODE BEGIN 2 */
	
	HAL_UART_Receive_IT(&huart1,&aRxBuffer1,1); 	//enable uart	

	printf(" mian \r\n");

	Get_SDCard_Capacity();	//Get used memory and choose formatting



  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  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 \r\n");
			HAL_Delay(500);
		}			
    /* USER CODE END WHILE */
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

SD card write function

void WritetoSD(BYTE write_buff[],uint8_t bufSize)
{
	FATFS fs;
	FIL file;
	uint8_t res=0;
	UINT Bw;	
	
	res = SD_init();		//SD card initialization
	
	if(res == 1)
	{
		printf("SD Card Initialization Failed! \r\n");		
	}
	else
	{
		printf("SD Card initialization succeeded! \r\n");		
	}
	
	res=f_mount(&fs,"0:",1);		//mount
	
//	if(test_sd == 0) 		// For test formatting
	if(res == FR_NO_FILESYSTEM)		//No file system, formatting
	{
//		test_sd =1; 				// For test formatting
		printf("No file system! \r\n");		
		res = f_mkfs("", 0, 0);		//Format sd card
		if(res == FR_OK)
		{
			printf("Successfully formatted! \r\n");		
			res = f_mount(NULL,"0:",1); 		//Unmount after formatting
			res = f_mount(&fs,"0:",1);			//remount	
			if(res == FR_OK)
			{
				printf("SD Card mounted successfully for file write test!\r\n");
			}	
		}
		else
		{
			printf("format failure! \r\n");		
		}
	}
	else if(res == FR_OK)
	{
		printf("Mount Successful! \r\n");		
	}
	else
	{
		printf("Mount failed! \r\n");
	}	
	
	res = f_open(&file,SD_FileName,FA_OPEN_ALWAYS |FA_WRITE);
	if((res & FR_DENIED) == FR_DENIED)
	{
		printf("Card Storage Full, Write Failed!\r\n");		
	}
	
	f_lseek(&file, f_size(&file));//Ensure that word writes do not overwrite previous data
	if(res == FR_OK)
	{
		printf("Open Successfully/Create file successful! \r\n");		
		res = f_write(&file,write_buff,bufSize,&Bw);		//Write data to SD card
		if(res == FR_OK)
		{
			printf("File written successfully! \r\n");			
		}
		else
		{
			printf("File write failed! \r\n");
		}		
	}
	else
	{
		printf("fail to open file!\r\n");
	}	
	
	f_close(&file);						//Close File		
	f_mount(NULL,"0:",1);		 //unmount
	
}


4. Experimentation Thoughts

This experiment is not difficult, but it is easy to make mistakes because of minor improper operations. When I was doing the experiment, I repeated it many times before I finally succeeded, which is a valuable experience.

Reference

https://blog.csdn.net/ZHONGCAI0901/article/details/113190393

Topics: Single-Chip Microcomputer stm32