本帖最后由 SJZhu 于 2024-10-6 12:04 编辑
STM32H7S78-DK板载了SD卡接口。支持microSD 4gb或更大容量的卡可以插入到插座(CN13)中。STM32H7S7L8H6H通过SDMMC1接口中的四个数据位、CLK和CMD信号与microSD进行通信™卡。SD_Detect信号检测卡插入。当microSD™卡插入时,SD_Detect级别为LOW,否则为HIGH。
在图形化配置界面:
最后还有一个GPIO用于SD卡检测:
点击保存,自动生成代码。
/**
* [url=home.php?mod=space&uid=247401]@brief[/url] SDMMC1 Initialization Function
* @param None
* @retval None
*/
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 */
}
通过调用FATFS_LinkDriver(&SD_Driver, SDPath)来初始化FatFs。
检测SD卡是否插入的函数:
static uint8_t SD_IsDetected(void)
{
uint8_t ret;
if (HAL_GPIO_ReadPin(SD_GPIO_PORT, PinDetect) == GPIO_PIN_RESET)
{
ret = HAL_ERROR;
}
else
{
ret = HAL_OK;
}
return ret;
}
接下来就可以正常读写SD卡:
/**
* [url=home.php?mod=space&uid=247401]@brief[/url] File system : file operation
* @retval File operation result
*/
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);
if((bytesread > 0) && (res == FR_OK))
{
/* Close the open text file */
f_close(&SDFile);
/* Compare read data with the expected data */
if(bytesread == byteswritten)
{
/* Success of the demo: no error occurrence */
return 0;
}
}
}
}
}
}
/* Error */
return -1;
}
通过读卡器把SD卡插入电脑后,可以看到TXT文件:
|