Skip to main content
Visitor II
May 28, 2020
Question

STM32F446 + DMA + FATFS + SDIO

  • May 28, 2020
  • 4 replies
  • 818 views

Hello everybody,

using Fatfs and f_write, when writing the file "1, 2, 3, 4" to the SDCard, I can see that what is written on the SDCard is "0,0,0,0,1,2,3,4" . What layer is inserting the 4 "0" at the beginning of the file and why ? Is it an 32bits alignment problem , Obviously, the f_read reads this 4 "0" header and leads to an error when verifying the data.

Thanks for your help.

o.

    This topic has been closed for replies.

    4 replies

    Graduate II
    May 28, 2020

    Might be more obvious why if you show the code.

    Perhaps alignment, but could be how you f_open() the file, and if it tries to append.

    papagenoAuthor
    Visitor II
    May 28, 2020

    Thanks Clive,

    Here is the code, nothing new, following some classical examples. I hope it helps. I was hoping to find the exact string in the file but editing the content shows nul nul nul nul This is Test programming

    char bufferwr[30] = "This is Test programming\n\r";

    char bufferrd[30];

    .

    .

    .

    .

    res = BSP_SD_Init();

    if(res != FR_OK)

    {

    Error_Handler();

    }

    res = f_mount(&SDFatFS, "", 1);

    if(res != FR_OK)

    {

    Error_Handler();

    }

    res = f_open(&myFile, "test1.txt", FA_OPEN_ALWAYS| FA_WRITE | FA_READ);

    if(res != FR_OK)

    {

    Error_Handler();

    }

    res = f_lseek(&myFile, sizeof(&myFile));

    if(res != FR_OK)

    {

    Error_Handler();

    }

    res = f_write(&myFile, bufferwr, 30, (UINT*)&byteswritten);

    if((byteswritten == 0) || (res != FR_OK))

    {

    Error_Handler();

    }

    res = f_close(&myFile);

    if(res != FR_OK)

    {

    Error_Handler();

    }

    res = f_open(&myFile, "test1.txt", FA_READ);

    if(res != FR_OK)

    {

    Error_Handler();

    }

    res = f_read(&myFile, bufferrd, 30, (UINT*)&bytesread);

    if((bytesread == 0) || (res != FR_OK)) /* EOF or Error */

    {

    Error_Handler();

    }

    res = f_close(&myFile);

    if(res != FR_OK)

    {

    Error_Handler();

    }

    res = f_mount(0, "", 1);

    if(res != FR_OK)

    {

    Error_Handler();

    }

    Super User
    May 28, 2020

    > res = f_lseek(&myFile, sizeof(&myFile));

    This moves the write pointer to byte 4 and is unlikely to be what you intended. Since you just want to write at the beginning of the file, use offset of 0 (or probably just omit this line).

    Graduate II
    May 28, 2020

    If you REALLY want to seek to the end of the file, surely

    res = f_lseek(&myFile, f_size(&myFile));

    papagenoAuthor
    Visitor II
    May 28, 2020

    Thanks you guys for your answers. To be honest, I was wondering why using the f_lseek in the example i copied.... Your answers make sense to me now. Thanks again Clive and TDK.