1. CUBEMX配置如下
2022.7.9添加:这里硬件流控建议打开,如果写入不成功,调试的时候运行到hsd->ErrorCode |= HAL_SD_ERROR_TX_UNDERRUN;那就是硬件流控设置的问题,参考L4参考手册里的如下内容:
45.7 HW flow control
The HW flow control functionality is used to avoid FIFO underrun (TX mode) and overrun
(RX mode) errors.
The behavior is to stop SDMMC_CK and freeze SDMMC state machines. The data transfer
is stalled while the FIFO is unable to transmit or receive data. Only state machines clocked
by SDMMCCLK are frozen, the APB2 interface is still alive. The FIFO can thus be filled or
emptied even if flow control is activated.
To enable HW flow control, the SDMMC_CLKCR[14] register bit must be set to 1. After reset
Flow Control is disabled
2. 测试代码
读写代码之间要判断状态或者延时
#include "main.h"
#include "sdio.h"
#include "usart.h"
#include "gpio.h"
#include <stdio.h>
void SystemClock_Config(void);
int fputc(int ch, FILE *f) //串口重定向
{
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xffff);
return ch;
}
uint8_t Status;
uint8_t read_buf[512];
uint8_t write_buf[512];
int main(void)
{
HAL_Init();
SystemClock_Config();
MX_GPIO_Init();
MX_SDIO_SD_Init();
MX_USART1_UART_Init();
for(uint16_t i = 0; i < 512; i++)
{
write_buf[i] = i % 256;
}
// 向SD卡块写入数据
printf("------------------- Write SD card block data Test ------------------\r\n");
Status = HAL_SD_WriteBlocks(&hsd,(uint8_t *)write_buf,0,1,0xffff);
if(Status == 0)
{
printf("Write block data ok \r\n" );
}
else
{
printf("Write block data fail!\r\n " );
}
while(HAL_SD_GetCardState(&hsd) != HAL_SD_CARD_TRANSFER);//等待传输完成
//读取数据
printf("------------------- Read SD card block data Test ------------------\r\n");
Status = HAL_SD_ReadBlocks(&hsd,(uint8_t *)read_buf,0,1,0xffff);
if(Status == 0)
{
printf("Read block data ok \r\n" );
for(uint16_t i = 0; i < 512; i++)
{
printf("0x%02x ", read_buf[i]);
if((i+1)%16 == 0)
{
printf("\r\n");
}
}
}
else
{
printf("Read block data fail!\r\n " );
}
while (1)
{
HAL_GPIO_TogglePin(GPIOI,GPIO_PIN_3); //LED blinblin!!
HAL_Delay(400);
}
}
PS:DMA方式还在纠结中,不知道为什么,写入好使但是读取不好使。读取时会卡在SDIO中断里不跳出来。再看看吧。