5

How do I store floats in flash and how do I read them from there? (I need a look-up table for pairs of float values.)

The storing part doesn't seem to be so difficult as this compiles:

PROGMEM float value1 = 1.23456;

But how do I read them? Do I need to copy them byte by byte to a float variable, or is there a better way? (I am using an Arduino ATmega 328p with 4-byte floats.)

4

There is a helper macro in avr-libc that is designed just for this purpose:

#define pgm_read_float_near(address_short) __LPM_float((uint16_t)(address_short))

Read a float from the program space with a 16-bit (near) address.

Note
    The address is a byte address. The address is in the program space. 

Use it like:

PROGMEM float pi=3.141592653;  // constant value in flash
float diameter = 24.332154;    // variable user value

float circumference = diameter * pgm_read_float_near(&pi);
1

I realize that the OP asked about a single value, but I thought I'd add info on retrieving from an array.

const float pmdata[] PROGMEM = {1.0, 2.0, 3.0};

then retrieve thusly:

float val = pgm_read_float(&pmdata[idx]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.