【前言】
开发板上板载了SD卡插座,这一篇分享如何驱动SD卡。
1、打开stm32cubeMX打开SD,但是不让生成初始化代码,初始化,由BSP工程的代码来实现。
2、添加bsp的sd卡驱动文件到工程中:
3、添加sd的中断到stm32l5xxit.c中
void EXTI2_IRQHandler(void)
{
BSP_SD_DETECT_IRQHandler(0);
}
void SDMMC1_IRQHandler(void)
{
BSP_SD_IRQHandler(0);
}
4、添加sd测试函数:
#include "main.h"
#include "stdio.h"
#define SD_CARD_PRESENCE_POLLING_MODE 0
#define SD_CARD_PRESENCE_INTERRUPT_MODE 1
#define SD_CARD_PRESENCE_VALIDATION_MODE SD_CARD_PRESENCE_INTERRUPT_MODE
#define BLOCK_START_ADDR 0 /* Block start address */
#define NUM_OF_BLOCKS 5 /* Total number of blocks */
#define BUFFER_WORDS_SIZE ((BLOCKSIZE * NUM_OF_BLOCKS) >> 2) /* Total data size in bytes */
__IO uint32_t SDWriteStatus = 0, SDReadStatus = 0, SDDetectStatus = 0, SDDetectIT = 0;
void SD_demo(void)
{
int32_t SD_state = BSP_ERROR_NONE;
SD_state = BSP_SD_Init(0);
#if (SD_CARD_PRESENCE_VALIDATION_MODE == SD_CARD_PRESENCE_INTERRUPT_MODE)
if (SD_state == BSP_ERROR_NONE)
{
SD_state = BSP_SD_DetectITConfig(0);
}
#endif
if (SD_state != BSP_ERROR_NONE)
{
if (SD_state == BSP_ERROR_UNKNOWN_COMPONENT)
{
printf("SD shall be inserted before");
printf("running test.\r\n");
printf("SD Test Aborted.\r\n");
}
else
{
printf("SD Initialization : FAIL.\r\n");
printf("SD Test Aborted.\r\n");
}
}
else
{
printf("SD Initialization : OK.\r\n");
}
}
/**
* [url=home.php?mod=space&uid=247401]@brief[/url] Tx Transfer completed callback
* @param Instance SD Instance
* @retval None
*/
void BSP_SD_WriteCpltCallback(uint32_t Instance)
{
if (Instance == 0)
{
SDWriteStatus = 1;
}
}
/**
* @brief Rx Transfer completed callback
* @param Instance SD Instance
* @retval None
*/
void BSP_SD_ReadCpltCallback(uint32_t Instance)
{
if (Instance == 0)
{
SDReadStatus = 1;
}
}
/**
* @brief BSP SD Callback.
* @param Instance SD Instance
* @param Status Pin status
* @retval None.
*/
void BSP_SD_DetectCallback(uint32_t Instance, uint32_t Status)
{
if (Instance == 0)
{
SDDetectIT = 1;
SDDetectStatus = Status;
}
}
/**
* @brief SDMMC error callback
* @param None
* @retval None
*/
void HAL_SD_ErrorCallback(SD_HandleTypeDef *hsd)
{
Error_Handler();
}
在main.c中添加sd_demo
下载到开发板上,可以看到SD初始化成功:
|