cancel
Showing results for 
Search instead for 
Did you mean: 

FatFS FA_CREATE_ALWAYS not working when file already exists

manurp
Associate II

Hi, I'm currently working on adding external memory to a Nucleo STM32F446RE board through 4bit SDIO using the WaveShare microSD BB: https://www.waveshare.com/wiki/Micro_SD_Storage_Board.

I created my project with STM32CubeMX configuring SDIO and FatFS without DMA for the moment (it will come once I made sure I understand the functionning of the FatFS library enough). I will write audio signals to it and then read it in a loop.

My configuration:

SDIO 4bit bus with a SDIOCLK clock divide factor of 4

FatFS (SD card) with MAX_SS of 4096

I am also using a class 10 SanDiskUltra 16GB microSDHC if that matters

I am trying to write multiple chunks of 16kB of data, having formatted the SD card to a 16kB cluster size with Windows 10, but I am having trouble with this simple operation (maybe not that simple after all). I have tried the FA_WRITE | FA_CREATE_ALWAYS flag, but for some reason it most of the time wont return FR_OK when writing. I have a loop where I write 4 times, and as a result I either get no write, or the first, sometimes the second also.

Here is my code:

/* USER CODE BEGIN 0 */
int16_t sd_buf [8192]; //16kB 
 
FATFS myFatFS;	// FatFS
FIL myFile;			// File
UINT myBytes; 	// Number of bytes written
char myFileName[] = "TEST1.txt";	
 
/* USER CODE END 0 */
...
 /* USER CODE BEGIN 2 */
 
for(int i = 0; i < RAM_BUFFER_SIZE; i++){
	sd_buf[i] = 2047;
}
	
if(f_mount(&myFatFS, SDPath, 1) == FR_OK )
{
	printf("\n\nFatFS mounted successfully!\r\n");
	int timeZero = HAL_GetTick(); // Time to open and close 5 times 
	if( f_open(&myFile, myFileName, FA_WRITE | FA_CREATE_ALWAYS) == FR_OK)
	{
		HAL_Delay(1000);
		printf("\nFile created successfully:\n\r");
		for(int i = 0; i < 4; i++){
			int t0 = HAL_GetTick();
			if (f_write(&myFile, sd_buf, sizeof(sd_buf), &myBytes)== FR_OK){
				int writeTime = HAL_GetTick() - t0;
				printf("%d: Wrote 16kB to file in %d ms!\n\r", i, writeTime);
				HAL_Delay(100);
			}
		}
		f_close(&myFile);
		printf("File closed.\n\r");
	}
	else 
			printf("\nERROR OPENING FILE\n\r");	
}
else // SD card not detected on pin PB8
{
	printf("Error mounting FatFS\r\n");
}
	
  /* USER CODE END 2 */

Using FA_OPEN_ALWAYS looked like it was more responsive if I refered to the return of FR_OK by each f_write. However, looking at the SD card content, I realise that even though I'm supposed to have written 64kB, my file is empty at 0kB.

Note that I never unmount the FatFS, is that a problem, considering I only interface with 1 card?

What am I doing wrong here?

0 REPLIES 0