一、准备工作
有关CUBEMX的初始化配置,参见我的另一篇blog:【STM32+HAL】CUBEMX初始化配置
二、所用工具
1、芯片: STM32F407ZGT6
2、IDE: MDK-Keil软件
3、库文件:STM32F4xxHAL库
三、实现功能
实现用DMA读写SD卡内容
四、HAL库配置
1、开启SDIO
模式配置为1bit,开启DMA传输,开启中断
2、开启串口通信
至此,HAL库配置完毕
五、Keil填写代码
1、sdio.c
/* USER CODE BEGIN 0 */
#include "stdio.h"
uint8_t TX[BLOCKSIZE],RX[BLOCKSIZE];
/* USER CODE END 0 */
/* USER CODE BEGIN 1 */
/*SD卡DMA写入测试函数*/
void SDCard_TestWrite_DMA(void)
{
// printf("\r\n*** DMA Writing blocks ***\r\n");
uint32_t BlockCount = 1;
uint16_t BlockAddr = 6;
for(uint16_t i=0;i<BLOCKSIZE; i++)
TX[i] = i;
HAL_SD_WriteBlocks_DMA(&hsd, TX, BlockAddr, BlockCount);
}
/*SD卡DMA读取测试函数*/
void SDCard_TestRead_DMA(void)
{
// printf("\r\n*** DMA Reading blocks ***\r\n");
uint32_t BlockCount=1;
uint16_t BlockAddr=6;
HAL_SD_ReadBlocks_DMA(&hsd, RX, BlockAddr, BlockCount);
}
/*DMA Tx传输完成回调*/
void HAL_SD_TxCpltCallback(SD_HandleTypeDef *hsd)
{
printf("DMA Write to block 6, OK\r\n");
printf("Data in [0:5] is: ");
for (uint16_t j=0; j<=5;j++)
{
printf("%d,", TX[j]);
}
printf("\r\n");
}
/*DMA Rx传输完成回调*/
void HAL_SD_RxCpltCallback(SD_HandleTypeDef *hsd)
{
printf("DMA Read block 6, OK\r\n");
printf("Data in [0:5] is: ");
for (uint16_t j=0; j<=5;j++)
{
printf("%d,", RX[j]);
}
printf("\r\n");
}
/*SD卡擦除测试*/
void SDCard_EraseBlocks(void)
{
uint32_t BlockAddrStart=0;
uint32_t BlockAddrEnd=10;
printf("\r\n*** Erasing blocks ***\r\n");
if(HAL_SD_Erase(&hsd, BlockAddrStart, BlockAddrEnd)==HAL_OK)
printf("Erasing blocks,OK\r\n");
else
printf("Erasing blocks,fail\r\n");
HAL_SD_CardStateTypeDef cardState=HAL_SD_GetCardState(&hsd);
printf("GetCardState()= %d\r\n", cardState);
while(cardState != HAL_SD_CARD_TRANSFER)
{
HAL_Delay(1);
cardState=HAL_SD_GetCardState(&hsd);
}
printf("Blocks 0-10 is erased.\r\n");
}
/* USER CODE END 1 */
2、sdio.h
/*sdio.h中声明函数*/
void SDCard_TestRead(void);
void SDCard_TestWrite(void);
void SDCard_ShowInfo(void);
void SDCard_EraseBlocks(void);
void SDCard_TestWrite_DMA(void);
void SDCard_TestRead_DMA(void);
3、main.c
SDCard_TestWrite_DMA();
HAL_Delay(500);
SDCard_EraseBlocks();
HAL_Delay(500);
SDCard_TestRead_DMA();
/* USER CODE END 2 */
六、巨人之肩
【STM32+HAL】利用SDIO将大量数据存入SD卡,并根据需要读出
STM32CubeMX教程27 SDIO - 读写SD卡
七、源码提供
资源【STM32+HAL】SDIO模式读写SD卡
八、结语
本人能力有限,代码未必是最优解,若有可改进之处望在评论区留言,采纳有赏~