STM32F429 SD卡初始化 ,用标准库函数
时间: 2024-01-28 08:39:10 浏览: 34
以下是STM32F429 SD卡初始化的代码示例,使用标准库函数。
```
#include "stm32f4xx.h"
#include "stm32f4xx_gpio.h"
#include "stm32f4xx_sdio.h"
#include "stm32f4xx_rcc.h"
#define SD_DETECT_PIN GPIO_Pin_13
#define SD_DETECT_GPIO_PORT GPIOC
#define SD_DETECT_GPIO_CLK RCC_AHB1Periph_GPIOC
void SD_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* Enable GPIOs clock */
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC | RCC_AHB1Periph_GPIOD | RCC_AHB1Periph_GPIOG, ENABLE);
/* Configure SD_DETECT_PIN pin: SD Card detect pin */
GPIO_InitStructure.GPIO_Pin = SD_DETECT_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(SD_DETECT_GPIO_PORT, &GPIO_InitStructure);
/* Configure SD_SPI_CS_PIN pin: SD Card CS pin */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOD, &GPIO_InitStructure);
/* Configure SD_SPI_SCK_PIN pin: SD Card SCK pin */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7;
GPIO_Init(GPIOC, &GPIO_InitStructure);
/* Configure SD_SPI_MISO_PIN pin: SD Card MISO pin */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_Init(GPIOC, &GPIO_InitStructure);
/* Configure SD_SPI_MOSI_PIN pin: SD Card MOSI pin */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
void SDIO_Configuration(void)
{
SDIO_InitTypeDef SDIO_InitStructure;
/* Enable SDIO clock */
RCC_APB2PeriphClockCmd(RCC_APB2Periph_SDIO, ENABLE);
/* Configure SDIO peripheral */
SDIO_InitStructure.SDIO_ClockDiv = SDIO_TRANSFER_CLK_DIV;
SDIO_InitStructure.SDIO_ClockEdge = SDIO_ClockEdge_Rising;
SDIO_InitStructure.SDIO_ClockBypass = SDIO_ClockBypass_Disable;
SDIO_InitStructure.SDIO_ClockPowerSave = SDIO_ClockPowerSave_Disable;
SDIO_InitStructure.SDIO_BusWide = SDIO_BusWide_1b;
SDIO_InitStructure.SDIO_HardwareFlowControl = SDIO_HardwareFlowControl_Disable;
SDIO_Init(&SDIO_InitStructure);
}
void SD_LowLevel_Init(void)
{
/* GPIO initialization */
SD_GPIO_Init();
/* SDIO initialization */
SDIO_Configuration();
}
int SD_Init(void)
{
uint32_t resp = 0;
uint8_t cmd = 0;
/* SD Low Level Init */
SD_LowLevel_Init();
/* Initialize SD Card */
if (SD_InitCard() == SD_OK)
{
/* Get Card information */
if (SD_GetCardInfo(&CardInfo) == SD_OK)
{
/* Select Card */
if (SD_SelectDeselect((uint32_t) (CardInfo.RCA << 16)) == SD_OK)
{
/* Set Card to High Speed Mode */
if (SD_EnableWideBusOperation(SDIO_BusWide_4b) == SD_OK)
{
/* SD Card initialized successfully */
return 0;
}
}
}
}
/* SD Card initialization failed */
return -1;
}
```
在以上代码中,我们首先定义了SD卡检测引脚和SD卡初始化所需的GPIO引脚。然后我们实现了一个SD_GPIO_Init函数,这个函数用于初始化SD卡相关的GPIO引脚。
接着,我们实现了一个SDIO_Configuration函数,这个函数用于配置SDIO外设。
最后,我们实现了一个SD_LowLevel_Init函数,这个函数用于执行SD卡的低级初始化。
最终,我们通过SD_Init函数来初始化SD卡,如果初始化成功,则返回0,否则返回-1。