Search code examples
stm32fatfs

stm32f4 fatfs f_write whitemarks


Im struggling with fatfs on stm32f4. With no problem i can mount, create file and write on it by : char my_data[]="hello world" and in windows file shows normally but when i try use code as loger :

float bmp180Pressure=1000.1;
char presur_1[6];//bufor znakow do konwersji
sprintf(presur_1,"%0.1f",bmp180Pressure);
char new_line[]="\n\r";

if(f_mount(&myFat, SDPath, 1)== FR_OK)
{
    f_open(&myFile, "dane.txt", FA_READ|FA_WRITE); 
    f_lseek(&myFile, f_size(&myFile));//sets end of data
    f_write(&myFile, presur_1, 6, &byteCount);
    f_write(&myFile, new_line,4, &byteCount);
    f_close(&myFile);
    HAL_GPIO_TogglePin(GPIOD, GPIO_PIN_15);
}

When i was read from computer i have :top : notepad ++ buttom :windows notepad


Solution

  • There are at least two problems in your code:

    The string for the number is too short. C strings are terminated with a null byte. So presur_1 needs to be at least 7 bytes long (6 for the number and 1 for the null byte). Since it's only 6 bytes long, sprintf will write beyond the allocated length and destroy some other data.

    The string for the newline is initialized with a string of 2 characters (plus the null byte). However, you write 4 characters to the file. So in addition to the newline, a NUL character and a garbage byte will end up in the file.

    The fixed code looks like this:

    float bmp180Pressure = 1000.1;
    char presur_1[20];//bufor znakow do konwersji
    int presur_1_len = sprintf(presur_1,"%0.1f\n\r",bmp180Pressure);
    
    if(f_mount(&myFat, SDPath, 1)== FR_OK)
    {
        f_open(&myFile, "dane.txt", FA_READ|FA_WRITE); 
        f_lseek(&myFile, f_size(&myFile));//sets end of data
        f_write(&myFile, presur_1, presur_1_len, &byteCount);
        f_close(&myFile);
        HAL_GPIO_TogglePin(GPIOD, GPIO_PIN_15);
    }