Home > OS >  SdFat write floats to file ESP32
SdFat write floats to file ESP32

Time:11-11

I Need to write float or Strings value into the SDVolume Cache in SDFAT library, I'm using ESP32 with SdCard module.

  uint8_t* pCache = (uint8_t*)sd.vol()->cacheClear();
  memset(pCache, ' ', 512);
  for (uint16_t i = 0; i < 512; i  = 4) {
    
    pCache[i   0] = 'r'; // I Need to write a Float value or String into this cell
    pCache[i   1] = ',';
    pCache[i   2] = '0';
    pCache[i   3] = '\n';
  }

Libray link: https://github.com/greiman/SdFat

CodePudding user response:

First:

// I Need to write a Float value or String into this cell

makes no sense - that "cell" is a single character, like 'e'. How do you write a full float value into a single character?

You probably just want to fill pCache with a string representation of your float. So do that!

We've got all C at our disposal, so let's use a somewhat memory efficient method:

std::to_chars is the C way to convert numeric values to strings. Something like

#include <charconv>
…
    std::to_chars(pCache, pCache 512-1, floatvalue);

would be appropriate.

Couple of things:

  • You need to zero-terminate strings if your needs to be able to know where they end. So, instead of memset(pCache, ' ', 512), memset(pCache, 0, 512); would be more sensible.
  • Are you sure your even using the right functions? vol()->cacheClear() is pretty unambigously marked as "do not use in your application" here! It also seems to be very unusual to me that you would write your string to some block device cache instead of getting a buffer for a file from the file system, or passing a buffer to the file system to write to a file.
  • Related