STM32 USB SD读卡器(SDIO)
2020-10-29 来源:eefocus
这次是做一个SD卡的USB读卡器的功能,我们就在上次NAND Flash模拟出的U盘的工程上修改了,这样的话只要修改一小部分了。
工程的绝大部分不需要修改,只要将fsmc_nand.c文件移除工程,添加上官方的关于SDIO的SD卡的驱动代码文件stm32_eval_sdio_sd.c,我讨厌出现eval,所以将该文件直接改为sdio_sdcard.c。同时,既然我们使用SDIO来驱动SD卡,所以在外设库文件组里要添加stm32_sdio.c文件,否则会出现很多未定错误。
STM32 USB SD读卡器(SDIO)
我们接下去修改的就只有mass_mal.c这个文件了。更NAND Flash工程一样,我们改成简洁点:
uint32_t Mass_Memory_Size[2];
uint32_t Mass_Block_Size[2];
uint32_t Mass_Block_Count[2];
__IO uint32_t Status = 0;
#ifdef USE_STM3210E_EVAL
SD_CardInfo SDCardInfo;
#endif
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/*******************************************************************************
* Function Name : MAL_Init
* Description : 初始化STM32的媒体设备
* Input : lun
* Output : None
* Return : None
*******************************************************************************/
uint16_t MAL_Init(uint8_t lun)
{
uint16_t status = MAL_OK;
switch (lun)
{
case 0: //SD卡
Status = SD_Init(); //调用SD初始化函数
break;
default:
return MAL_FAIL; //都不是
}
return status;
}
uint16_t MAL_Write(uint8_t lun, uint32_t Memory_Offset, uint32_t *Writebuff, uint16_t Transfer_Length)
{
switch (lun)
{
case 0:
Status = SD_WriteBlock((uint8_t*)Writebuff, Memory_Offset, Transfer_Length);
SD_WaitWriteOperation(); //等待dma传输结束
while(SD_GetStatus() != SD_TRANSFER_OK); //等待sdio到sd卡传输结束
if ( Status != SD_OK )
{
return MAL_FAIL;
}
break;
default:
return MAL_FAIL;
}
return MAL_OK;
}
uint16_t MAL_Read(uint8_t lun, uint32_t Memory_Offset, uint32_t *Readbuff, uint16_t Transfer_Length)
{
switch (lun)
{
case 0:
Status = SD_ReadBlock((uint8_t*)Readbuff, Memory_Offset, Transfer_Length);
SD_WaitReadOperation(); //循环查询dma传输是否结束
while(SD_GetStatus() != SD_TRANSFER_OK);
if ( Status != SD_OK )
{
return MAL_FAIL;
}
break;
default:
return MAL_FAIL;
}
return MAL_OK;
}
uint16_t MAL_GetStatus (uint8_t lun)
{
uint32_t temp_block_mul = 0;
uint32_t DeviceSizeMul = 0;
if (lun == 0)
{
#ifdef USE_STM3210E_EVAL
if (SD_Init() == SD_OK)
{
SD_GetCardInfo(&SDCardInfo);
SD_SelectDeselect((uint32_t) (SDCardInfo.RCA << 16));
DeviceSizeMul = (SDCardInfo.SD_csd.DeviceSizeMul + 2);
if(SDCardInfo.CardType == SDIO_HIGH_CAPACITY_SD_CARD)
{
Mass_Block_Count[0] = (SDCardInfo.SD_csd.DeviceSize + 1) * 1024;
}
else
{
NumberOfBlocks = ((1 << (SDCardInfo.SD_csd.RdBlockLen)) / 512);
Mass_Block_Count[0] = ((SDCardInfo.SD_csd.DeviceSize + 1) * (1 << DeviceSizeMul) << (NumberOfBlocks/2));
}
Mass_Block_Size[0] = 512;
Status = SD_SelectDeselect((uint32_t) (SDCardInfo.RCA << 16));
Status = SD_EnableWideBusOperation(SDIO_BusWide_4b);
if ( Status != SD_OK )
{
return MAL_FAIL;
}
Mass_Memory_Size[0] = Mass_Block_Count[0] * Mass_Block_Size[0];
LED2_ON();
return MAL_OK;
}
else
{
LED2_OFF();
}
}
return MAL_FAIL;
}
这样SDIO接口的SD卡读卡器就修改完毕了。我使用8G的SD卡测试的,不知道为什么写这么慢,才60KB/秒左右,读的速度为230KB/秒左右。
STM32 USB SD读卡器(SDIO) - ziye334 - ziye334的博客 STM32 USB SD读卡器(SDIO)