STM32F401 SDIO HAL driver初始化SD卡

STM32F4xx的HAL部分已经提供了SD的driver,初始化时的IO PIN等放在HAL_SD_MspInit。

void HAL_SD_MspInit(SD_HandleTypeDef *hsd)
{
	GPIO_InitTypeDef  GPIO_InitStruct;

	__HAL_RCC_GPIOC_CLK_ENABLE();
	__HAL_RCC_GPIOD_CLK_ENABLE();

	GPIO_InitStruct.Mode      = GPIO_MODE_AF_PP;
	GPIO_InitStruct.Pull      = GPIO_PULLUP;
	GPIO_InitStruct.Speed     = GPIO_SPEED_FAST;
	GPIO_InitStruct.Alternate = GPIO_AF12_SDIO;

	/*SDIO GPIO Configuration   
		PC8     ------> SDIO_D0
		PC9     ------> SDIO_D1
		PC10     ------> SDIO_D2
		PC11     ------> SDIO_D3
		PC12     ------> SDIO_CK
		PD2     ------> SDIO_CMD
		*/
	GPIO_InitStruct.Pin = GPIO_PIN_8 | GPIO_PIN_9 | GPIO_PIN_10 | GPIO_PIN_11 | GPIO_PIN_12;    
	HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
	GPIO_InitStruct.Pin = GPIO_PIN_2;    
	HAL_GPIO_Init(GPIOD, &GPIO_InitStruct);

	__HAL_RCC_SDIO_CLK_ENABLE(); 
	__SDIO_CLK_ENABLE();

	hsd->Instance = SDIO;
	hsd->Init.ClockEdge           = SDIO_CLOCK_EDGE_RISING;
	hsd->Init.ClockBypass         = SDIO_CLOCK_BYPASS_DISABLE;
	hsd->Init.ClockPowerSave      = SDIO_CLOCK_POWER_SAVE_DISABLE;
	hsd->Init.BusWide             = SDIO_BUS_WIDE_1B;
	hsd->Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE;
	hsd->Init.ClockDiv            = SDIO_TRANSFER_CLK_DIV;
}

定义两个变量

SD_HandleTypeDef hsd;
HAL_SD_CardInfoTypedef SDCardInfo;

main函数中初始化SD卡的相关代码:

__IO HAL_SD_ErrorTypedef errorstate = SD_OK;
	errorstate = HAL_SD_Init(&hsd, &SDCardInfo);
	if(SD_OK == errorstate)
	{
		errorstate = HAL_SD_WideBusOperation_Config(&hsd, SDIO_BUS_WIDE_4B);
		if(SD_OK != errorstate)
		{
			while(1);
		}
		....
	}

HAL_SD_Init()函数中会先调用HAL_SD_MspInit()初始化PIN和clk等。

需要注意的是初始化时bus width只能设置成1bit,然后通过

HAL_SD_WideBusOperation_Config(&hsd, SDIO_BUS_WIDE_4B)来切换成4位模式,在初始化时直接设置成4位是无效的。

完成以上工作后就可以通过HAL_SD_ReadBlocks()和HAL_SD_WriteBlocks()来完成block形式的读写操作了,需要FATFS的话可以参考其它例子。



你可能感兴趣的:(ARM,Cortex-M)