Electronic – Writing and Reading Hex Values to a Text file using FatFs

fathal-librarystm32f4

Currently i am working on STM32F479 Eval board. I have to collect data from sensor nodes and store it in a text file using FatFs. My sensor values are in Hexadecimal values. I am using STM32F4Cube HAL Library which includes FatFs. I am using f_write() function to pass these hex values to a text file. But it is storing as garbage values which is not as expected. When i use f_printf() it is working perfectly as expected (Hex values gets stored). But when reading again it shows some other values which is not the stored values. I have two questions.

  1. What is the perfect way to store Hex values in a text file and read the same from a text file using FatFs?

  2. Is there any other way like converting these hex values to char before passing it into a file and again reconverting after reading from a file?

My code:

uint8_t Buff[]; // Buffer to read data from Sensors 

uint32_t byteswritten;

f_write(&MyFile,Buff,sizeof(Buff),(void*)byteswritten); //But writing some other values

for(i=0;i<sizeof(Buff);i++)
{
    f_printf(&MyFile,Buff[i]); //Writing properly But reading throws unexpected values
}

Best Answer

This line makes a pointer from a random value on the stack, asking for a (Hard-) fault:

f_write(&MyFile,Buff,sizeof(Buff),(void*)byteswritten); 

Correct code would look like this:

UINT byteswritten;
f_write(&MyFile,Buff,sizeof(Buff),&byteswritten);

Note that f_write() writes data in binary to the file, not in hexadecimal.

That f_printf() line should give you a compiler warning like "make pointer from an integer without a cast", because it expects a string (pointer to char) as second argument.

Corrected line for hexadecimal output:

f_printf(&MyFile," %X",Buff[i]);