Skip to main content
Explorer
February 9, 2023
Question

Unable to close files in STM32 with USB MSC + FATFS

  • February 9, 2023
  • 3 replies
  • 1770 views

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?

    This topic has been closed for replies.

    3 replies

    Super User
    February 9, 2023

    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.

    MRey.1Author
    Explorer
    February 9, 2023

    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

    Super User
    February 10, 2023

    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

    MRey.1Author
    Explorer
    February 10, 2023

    0693W00000YATdSQAX.png

    MRey.1Author
    Explorer
    February 10, 2023

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