SOLVED How to store a float in EEPROM properly?

int tempAddress = 0
float temp;

void setup(){
EEPROM.get(tempAddress, temp);
}

void loop(){
if(EepromFlag){
EEPROM.put(tempAddress, temp);
EepromFlag = false;
}

...
...

}

//Gets Temp from user and turns eepromflag true

cant seem to get it to work

It might be that your snippet is just missing that crucial part, but your EepromFlag doesn’t seem to be set to true anywhere (apart from the comment), but was the data ever put into EEPROM at all?

Is it a local or a global variable?
If local, is it static?

the EEPROMflag is getting set true. I have tried the same thing but with int values rather than float and seems to work for positive value but not negative. idk wats going on.

They are all global.

This little test works as expected, so I’d think the issue must be with the code we can’t see :wink:

void setup() {
  Particle.function("put", put);
  Particle.function("get", get);
}

int put(const char* cmd) {
    float x = atof(cmd);
    
    Serial.printlnf("Storing to EEPROM: %f", x);
    EEPROM.put(0, x);
    
    return x;
}

int get(const char* dmy) {
    float x;
    
    EEPROM.get(0, x);
    Serial.printlnf("Retrieved from EEPROM: %f", x);

    return x;    
}

Are you maybe redeclaring float temp inside of your undisclosed function (locally) hiding the global variable?

3 Likes

If i declared temp at the top of my code like:

float temp;

when i call eeprom get will i need to state if temp == null then temp = 0 ?

Nope.

Have you tried my code?

Having a minimal test code - which you post as a whole - should be the first thing when you encounter unexpected behaviour.
If you can't reproduce the erronous behaviour with a minimal test code, you need to look at the rest of your original code.
If you still can't find it, let someone else have a look at the full code - with Web IDE posting a SHARE THIS REVISION link is a convenient way to do that.

BTW, what system version are you targeting?

3 Likes

I am targeting 0.7.0 and i have tired your code and it is working. Ill try figure out why mine is not working before posting a revision.

thanks for the code :smile:

Hey,

Thanks a ton! I got it to work, I actually found more clarity in this matter from one of your other replies on another thread (how to handle situation if EEPROM is empty and it is NAN)

#include <math.h>

void setup() {
  Particle.function("put", put);
  Particle.function("get", get);
  Particle.function("clear", clear);
}

int put(const char* cmd) {
    float x = atof(cmd);

    Serial.printlnf("Storing to EEPROM: %f", x);
    EEPROM.put(0, x);

    return x;
}

int get(const char* dmy) {
    float x;

    EEPROM.get(0, x);
    if(isnan(x)){
      Serial.printlnf("It is NAN");
    }
    else{
      Serial.printlnf("Retrieved from EEPROM: %f", x);
    }


    return x;
}

int clear(const char* comd){
  EEPROM.clear();
  Serial.printlnf("CLEARED");
  return 0;
}