Master the principle of SD card protocol and complete the data reading of SD card with STM32F103 (fat file mode)

Posted by njm on Fri, 24 Dec 2021 14:17:11 +0100

1, Principle of SD card protocol

1. Physical structure of SD card

General SD card includes five parts: storage unit, storage unit interface, power detection, card, interface controller and interface driver.

The storage unit is a storage data component, and the storage unit transmits data with the card control unit through the storage unit interface;
The power detection unit ensures that the SD card works at an appropriate voltage. In case of power failure or power on, it will reset the interface between the control unit and the storage unit;
The SD card and interface control unit control the operation state of the SD card, which includes 8 registers; The interface driver controls the input and output of the SD card pin.

2. SD card register

The SD card has a total of 8 registers for setting or representing SD card information.
These registers can only be accessed through corresponding commands. SDIO defines 64 commands, each of which has a special meaning and can realize a specific function. After receiving the command, the SD card modifies the internal registers of the SD card according to the command requirements. In program control, it only needs to send combined commands to realize the control and read-write operation of the SD card.

3. SD card read and write (SPI mode)

1. Send CMD17;
2. Receiving card response R1;
3. Receive data start token 0XFE;
4. Receiving data;
5. Receive two bytes of CRC. If CRC is not used, these two bytes can be discarded after reading.
6. After Prohibiting film selection, send 8 more clks;
The above is a typical process of reading SD card data. The writing of SD card is almost the same as reading data. The writing data is realized through CMD24. The specific process is as follows:
1. Send CMD24;
2. Receiving card response R1;
3. Send write data start token 0XFE;
4. Send data;
5. Send 2-byte pseudo CRC;
6. After Prohibiting film selection, send 8 more clks;
The above is a typical SD card writing process.

2, Experiment preparation and operation

1. Hardware preparation

SD card module and SD card

2. Connect


3. hal library and related code

Link: https://pan.baidu.com/s/1EpFh744MGUeSnjkz0b_KCw
Extraction code: 520g

3, Analysis of experimental results




When the file is written and the SD card is initialized for 11 times, a while will appear.

4, Code analysis

Main 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 the memory used and select format



  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {		
		WritetoSD(WriteBuffer,sizeof(WriteBuffer));			
		HAL_Delay(500);
		WriteBuffer[0] = WriteBuffer[0] +10;
		WriteBuffer[1] = WriteBuffer[1] +10;
		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, format
	{
//		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("Format succeeded! \r\n");		
			res = f_mount(NULL,"0:",1); 		//Unmount after formatting
			res = f_mount(&fs,"0:",1);			//Remount	
			if(res == FR_OK)
			{
				printf("SD The card has been successfully mounted and can be used for file writing test!\r\n");
			}	
		}
		else
		{
			printf("format failure! \r\n");		
		}
	}
	else if(res == FR_OK)
	{
		printf("Mount succeeded! \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("Memory card full, write failed!\r\n");		
	}
	
	f_lseek(&file, f_size(&file));//Make sure that writing words does not overwrite previous data
	if(res == FR_OK)
	{
		printf("Open successfully/File created successfully! \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 writing failed! \r\n");
		}		
	}
	else
	{
		printf("fail to open file!\r\n");
	}	
	
	f_close(&file);						//Close file		
	f_mount(NULL,"0:",1);		 //Unmount
	
}


The program first performs relevant initialization, outputs mian after completion, and then formats the SD card. After success, it enters the cycle and enters the SD card read-write function. It successively initializes, mounts, creates files, writes, writes more than 10 times, and outputs while.

5, Summary

In this experiment, there are many problems in initialization. After debugging, it is found that both SD card and STM32 need to be connected to 5V.

6, References

https://blog.csdn.net/m0_58414679/article/details/122036435

Topics: Single-Chip Microcomputer stm32