[Solved] A better way to write/read floats from PROGMEM?

Hello :),

A recent topic reminded me that I have a small question about PROGMEM and floats... I have a huge array of floats, and would like to store it in PROGMEM and read it back. I've read that PROGMEM doesn't like floats.

I found a crappy way that consist of converting floats to hex and then read it as it was floats. Example:

float f1 = 0.017452;

PROGMEM prog_int32_t f2 = 0x3C8EF77F; //that is 0.017452 in hex, as returned by the Serial.print below,

void setup()
{
  Serial.begin(9600);
  delay(1000);
  
  char str[12];
  sprintf(str, "0x%08lX\n", *(int32_t*)&f1 );
  Serial.print(str); //print 0x3C8EF77F
  
  Serial.print( __ELPM_float((int32_t)&f2), 6 ); //print 0.017452
}

void loop()
{
}

But is there a better way, which doesn't require to convert my whole float array to hex?

Of course I can (and did) make a script to Serial.print the converted array, so I just have to copy/paste it in my sketch, but I would prefer to not have to do that...

Thanks!


Edit: Why I haven't tried this before? It is said that PROGMEM doesn't support floats..but it does? Or am I missing something?

PROGMEM float f = 0.017452;

void setup()
{
  Serial.begin(9600);
  delay(1000);

  //print 0.017452, but seems to work for only a single value, not an array..
  Serial.print( f, 6 );

  //probably the correct way to do it, work for both single value and array.
  Serial.print( __ELPM_float(&f), 6 );
}

void loop()
{
}

This works fine for me:

float f[] PROGMEM = {0.017452, 3.14159};
  
const int floatCount = sizeof f / sizeof f[0];  // Number of elements

void setup()
{
  Serial.begin(9600);
  delay(1000);
  for (int i=0; i<floatCount; i++)
    Serial.println(pgm_read_float(&f[i]), 6 );
}

void loop()
{
}

http://arduiniana.org/libraries/flash/

johnwasser:
This works fine for me:

Yes I remember using this in combination with my hex array and it failed, then forgot to try it again with the float array… :slight_smile:

Yes I saw that library but, I try not using other libraries if I feel like I can do it yyself.

Thanks anyway :slight_smile:

Yes I saw that library but, I try not using other libraries if I feel like I can do it yyself.

There's nothing stopping you from looking at the library to see HOW something is done, when you are having trouble with the "do it yyself" part.