cembeddedfatfs

Write to file in binary on a microcontroller


I'm using a STM32476 Nucleo board, and right now I write some data from sensors in a readable file, but it's way too slow. To show some code of what I'm doing now:

static char buffer[LINE_MAX];
char* p = buffer;
p += sprintf(p, "%f,%f,%f,", s.ax.val, s.ay.val, s.az.val);
p += sprintf(p, "%f,%f,%f,", s.gx.val, s.gy.val, s.gz.val);
p += sprintf(p, " %f"DEGREE_UTF8"C\r\n", s.temperature);

int ret;

unsigned bytes_written=0;
if ((ret = f_write(&USERFile, buffer, length, &bytes_written)) != FR_OK || bytes_written != length) {
    hang("write failed: %d (written = %u)", ret, bytes_written);
}

How could I change this to write in binary instead?


Solution

  • In the most simplest form you just dump the data as is:

    float data = ...
    fwrite(&file, &data, sizeof data, &written);
    

    This of course doesn't handle endianness gracefully, and doesn't have any structure (you might want to look at more sophisticated formats for that, like CBOR).

    If I remember correctly, FatFS already does some buffering behind the scenes, but it could also be faster to memcpy all data to temporary buffer first and then write that. You need to experiment, if speed is your top priority.