cancel
Showing results for 
Search instead for 
Did you mean: 

Unable to close files in STM32 with USB MSC + FATFS

MRey.1
Associate III

I created a project to create, write, read and close a file in a USB stick, using a STM32F413 MCU. I used STM32CubeMX to generate the code. The relevant part of the code is this:

uint8_t text[]={"Hello world\r\n"},rbuff[50],test=0;

   switch(Appli_state)

   {

      case APPLICATION_READY:

         test+=f_mount(&USBDISKFatFs, (TCHAR const*)USBHPath, 1);

         test+=f_open(&MyFile, "FILE.txt", FA_CREATE_ALWAYS | FA_WRITE | FA_READ);

         test+=f_write(&MyFile, text, sizeof(text), (void *)&bytesw);

         f_lseek(&MyFile, 0);

         test+=f_read(&MyFile, rbuff, sizeof(text), (void *)&bytesr);

         test+=f_close(&MyFile);

         if(memcmp(text,rbuff,sizeof(text)))

            test++;

         break;

default:

break;

   }

   if(!test)

   {

      return test; //PASS

   }

   else

   {

      return test; //FAIL

   }

I´m confused, because I find that the "test" variable only stops being equal to zero after executing the f_close function. When I check the rbuff variable after the f_read function, I see that "rbuff" it has the same value as "text", and "test" is still zero. Meaning that the program has successfully mounted, created the file, opened it, wrote it and read it. However, f_close returns a fail value and when I unplug the USB stick and plug it on the PC, it's empty. The USB stick is formated as FAT32 I have no idea what could be causing this problem. Any ideas?

5 REPLIES 5
AScha.3
Chief II

why "all in one" ?

my way: write - close file . then open - read -- check read.

and separate result -> error , stop. to know, what is wrong, not just something ( += ) went wrong.

If you feel a post has answered your question, please click "Accept as Solution".

Thank you for answering

Actually, that is what I did at first, but every time I closed the file, it returned an error value

In fact, to make sure that f_close was the problem, I created a .txt file in the PC and then tried to read it. I could open and read it successfully. Only when I closed that file it retuned a value different from zero

If it helps, the error value of f_close is FR_DISK_ERR

AScha.3
Chief II

so there is no "write" at all. because at "close" buffers flushed and real write to disc. without close it can be just in buffers, no real write at all.

so check, there is no write protection and in Cube check , write is enabled.

(here my setting, just mkfs disabled.)

0693W00000YARgbQAH.png

If you feel a post has answered your question, please click "Accept as Solution".
MRey.1
Associate III

0693W00000YATdwQAH.pngOk, I checked and there doesn´t seem to be any write protection. You say it could be reading the write buffer vector?

0693W00000YATdSQAX.png