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.)
2 Answers 2
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);
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]);
-
what "&" means on &pmdataMuhammad Ikhwan Perwira– Muhammad Ikhwan Perwira2021年04月20日 06:38:31 +00:00Commented Apr 20, 2021 at 6:38