STM32U575 Writing to SD card fails after few times after re-insert
Hello,
I am using the SDMMC1 interface with DMA and FATFS and write data to an SD card. When starting my application with inserted SD card, everything works as expected (reliably and fast). I use FreeRTOS.
When ejecting the SD card during runtime, and re-inserting it, writing succeeds for 2-6 times, but stops working eventually, even after multiple re-initialisations and wait times. The only thing which works is to reset the whole MCU.
Here is what I do:
Before writing, I check the status of the SD card with HAL_SD_GetCardState():
/*
* Purpose:
* Waiting for the SD card to process requests
*/
fenrirStatus_t SD1_WaitForSDInterface(){
// Check current SD card state
HAL_SD_CardStateTypeDef sdState = HAL_SD_GetCardState(&hsd1);
if(sdState == HAL_SD_CARD_PROGRAMMING) {
// If state is currently in programming, wait for max 1 second
uint16_t startWait = osKernelGetTickCount();
while((osKernelGetTickCount() - startWait) < 1000 && sdState == HAL_SD_CARD_PROGRAMMING){
osDelay(75);
sdState = HAL_SD_GetCardState(&hsd1);
}
}
// when state is now in state ready to receive, return okay
switch(sdState){
case HAL_SD_CARD_TRANSFER:
case HAL_SD_CARD_STANDBY:
case HAL_SD_CARD_READY:
SD1_Interfae_Error_Counter = 0;
return fenrirOk;
case 0: // card was most likely disconnected
SD1_Status = SD_NotFound;
break;
default:
break;
};
return fenrirError;
}In case of ejected SD card, sdState will be 0 indicating no result. Next, I deinitialize the SD interface:
HAL_SD_Abort(&hsd1);
HAL_SD_DeInit(&hsd1);
HAL_SD_MspDeInit(&hsd1);Now I periodically check for the SD detect signal. As soon as it signals a present SD card, I call the same init functions as before:
HAL_SD_MspInit(&hsd1);
hsd1.ErrorCode = HAL_SD_ERROR_NONE;
hsd1.State = HAL_SD_STATE_RESET;
MX_SDMMC1_SD_Init();This also succeeds. After that, I mount my filesystem and my write attempts succeed for 2-6 times (usually 4).
But eventually, when checking for the SD card state with the following function calls, I am "stuck" in a timeout loop and do not get a response from the SD card.
HAL_SD_GetCardState -> SD_SendStatus -> SDMMC_CmdSendStatus -> SDMMC_GetCmdResp1
The loop:
do
{
if (count-- == 0U)
{
return SDMMC_ERROR_TIMEOUT;
}
sta_reg = SDMMCx->STA;
} while (((sta_reg & (SDMMC_FLAG_CCRCFAIL | SDMMC_FLAG_CMDREND | SDMMC_FLAG_CTIMEOUT |
SDMMC_FLAG_BUSYD0END)) == 0U) || ((sta_reg & SDMMC_FLAG_CMDACT) != 0U));
Maybe not relevant but here you can see that data is written after reinsertion.

I already tried a lot and I have no idea how to continue debugging this further. Any help is appreciated!
