本帖最后由 南来之风 于 2024-9-8 21:53 编辑
开发板上有MicroSD卡接口:
根据原理图初始化相应的PIN与时钟:
相应的初始化函数:- void MX_SDMMC1_SD_Init(void)
- {
- /* USER CODE BEGIN SDMMC1_Init 0 */
- /* USER CODE END SDMMC1_Init 0 */
- /* USER CODE BEGIN SDMMC1_Init 1 */
- /* USER CODE END SDMMC1_Init 1 */
- hsd1.Instance = SDMMC1;
- hsd1.Init.ClockEdge = SDMMC_CLOCK_EDGE_FALLING;
- hsd1.Init.ClockPowerSave = SDMMC_CLOCK_POWER_SAVE_DISABLE;
- hsd1.Init.BusWide = SDMMC_BUS_WIDE_4B;
- hsd1.Init.HardwareFlowControl = SDMMC_HARDWARE_FLOW_CONTROL_ENABLE;
- hsd1.Init.ClockDiv = 0x02;
- if (HAL_SD_Init(&hsd1) != HAL_OK)
- {
- Error_Handler();
- }
- /* USER CODE BEGIN SDMMC1_Init 2 */
- /* USER CODE END SDMMC1_Init 2 */
- }
接下来进行读写测试:
- static int32_t FS_FileOperations(void)
- {
- FRESULT res; /* FatFs function common result code */
- uint32_t byteswritten, bytesread; /* File write/read counts */
- uint8_t rtext[100]; /* File read buffer */
- /* Register the file system object to the FatFs module */
- if(f_mount(&SDFatFs, (TCHAR const*)SDPath, 0) == FR_OK)
- {
- /* Create and Open a new text file object with write access */
- if(f_open(&SDFile, "STM32.TXT", FA_CREATE_ALWAYS | FA_WRITE) == FR_OK)
- {
- /* Write data to the text file */
- res = f_write(&SDFile, (const void *)wtext, sizeof(wtext), (void *)&byteswritten);
- if((byteswritten > 0) && (res == FR_OK))
- {
- /* Close the open text file */
- f_close(&SDFile);
- /* Open the text file object with read access */
- if(f_open(&SDFile, "STM32.TXT", FA_READ) == FR_OK)
- {
- /* Read data from the text file */
- res = f_read(&SDFile, ( void *)rtext, sizeof(rtext), (void *)&bytesread);
- HAL_UART_Transmit(&huart4, "\r\n", sizeof("\r\n"), 0xffffffff);
- HAL_UART_Transmit(&huart4, rtext, strlen(rtext), 0xffffffff);
- if((bytesread > 0) && (res == FR_OK))
- {
- /* Close the open text file */
- f_close(&SDFile);
- /* Compare read data with the expected data */
- if(bytesread == byteswritten)
- {
- HAL_UART_Transmit(&huart4, "\r\nSuccess of the demo", sizeof("\r\n Success of the demo"), 0xffffffff);
- /* Success of the demo: no error occurrence */
- return 0;
- }
- }
- }
- }
- }
- }
- /* Error */
- return -1;
- }
实物展示:
|