I am trying to write to a file on an SD card using an STM32F401RET6 development board. I am using an SDIO adapter I got on amazon (https://www.amazon.ca/gp/product/B07C26YZPK/ref=oh_aui_detailpage_o06_s00?ie=UTF8&psc=1). In STM32CubeMX, I have enabled 1 bit SDIO and have set the FATFS middleware to SD Card. I changed nothing in the "Configuration" tab.
I am using the following code in "USER CODE BEGIN 2" (right above void main
's infinite loop) to write "Hello World!" to the SD card.
FATFS fs;
FIL file;
UINT bytesWritten;
FRESULT res;
res = f_mount(&fs, SDPath, 1);
PRINT_RESULT("Mounting filesystem", res);
if (res != FR_OK) return 1;
res = f_open(&file, "WRITE.TXT\0", FA_WRITE | FA_CREATE_ALWAYS);
PRINT_RESULT("Opening file", res);
if (res != FR_OK) return 1;
char data[] = "Hello World!\0";
res = f_write(&file, data, sizeof(data), &bytesWritten);
PRINT_RESULT("Writing file", res);
f_close(&file);
This code uses a macro I wrote to more easily log the results of these functions.
#define PRINT_RESULT(action, res) do { \
char msg[sizeof(action) + 6]; \
sprintf(msg, "%s: %03d\n", action, res); \
HAL_UART_Transmit(&huart2, (uint8_t *) msg, sizeof(msg), 100); \
} while (0);
When I upload and run this, I get the following in the serial monitor:
Mounting filesystem: 000
Opening file: 000
This means that mounting the filesystem and opening the file for writing both succeeded. However, the f_write
function never returns. When I put the SD card into my computer, I can see that the file was created but it is empty.
I can read files no problem but I can't write to them. I also tried f_puts
which didn't work either. I am using STM32CubeMX 4.27 and compiling with the generated Makefile
. I have tried several SD cards and all act the same.