# STM32 SDIO FATFS

I'm using SDIO (1-bit mode) with an STM32F429 Discovery board to read from and write to an SD card. The code below works, I've seen that it does, the problem is it seems to randomly choose when to work and when to fail. It always fails on the f_open stage. Each time I reset the board it either works or it doesn't. I've even tried putting the f_open part in a loop to see if it won't work after a couple of tries, but it fails all 10 times. The error it gives when it fails is FR_DISK_ERR.

if(f_mount(&SDFatFS, (TCHAR const*) SDPath, 0) != FR_OK){
Error_Handler();
HAL_GPIO_WritePin(R_LED_GPIO_Port, R_LED_Pin, GPIO_PIN_SET);
}
else{
res = f_open(&SDFile, "FILE.TXT", FA_READ | FA_OPEN_ALWAYS);
if(res != FR_OK){
printf("f_open r: %d\n", res);
Error_Handler();
HAL_GPIO_WritePin(R_LED_GPIO_Port, R_LED_Pin, GPIO_PIN_SET);
}
else{
res = f_read(&SDFile, readBuff, sizeof(readBuff), (void*) &bytesRead);
if((res != FR_OK) || (bytesRead == 0)){
printf("f_read: %d\n", res);
Error_Handler();
HAL_GPIO_WritePin(R_LED_GPIO_Port, R_LED_Pin, GPIO_PIN_SET);
}else{
printf("%s\n", readBuff);
HAL_GPIO_WritePin(G_LED_GPIO_Port, G_LED_Pin, GPIO_PIN_SET);
}
f_close(&SDFile);
}
}


Any advice would be appreciated, thanks!

UPDATE: If I force mount it (f_mount(&SDFatFS, (TCHAR const*) SDPath, 1)), it also fails on DISK_ERR so it seems the mounting process is the one failing, but I still see no pettern as to why. I put a 1s delay in start-up to give the SD card time to "get ready", I suppose, but no dice.

UPDATE: Added pull-ups to the D0 and CMD lines and it drastically increased the success to fail ratio to a more workable level.

• Standard recommendation in the face of bugs: use a debugger. – Marcus Müller Jul 22 '19 at 18:56
• (really, learn how to debug. That's a skill so useful it will pay back the time you spent acquiring it within days) – Marcus Müller Jul 22 '19 at 19:06
• Or at least, dig into the situation where the failure is declared. Try to trace it down to an unexpected reply from the card. See if maybe your setup either starts too soon when power is applied, or doesn't get the card back to a clean state if the MCU is reset. Make sure invalid assumptions about card behavior aren't being made. – Chris Stratton Jul 22 '19 at 19:14
• Detail what software you are using, please. – TimWescott Jul 22 '19 at 19:15
• I have been debugging, it doesn't tell me much. It goes into find_volume(), then it goes to a section that says the file system object is not valid. It then tries to find a FAT partition, fails to do so and returns a DISK_ERR. If the problem was the card isn't formatted correctly fine, but then it wouldn't work at all, would it? – BdT141 Jul 22 '19 at 19:19