Search code examples
arduinoeeprom

How to store negative numbers in EEPROM (Arduino IDE)?


I am trying to find a straightforward way to store negative values in EEPROM, integer values ranging from -20 to 20. I have been using EEPROM.write and EEPROM.read functions to store strings one character at a time, but I am having trouble with negative numbers. I figure I only need one byte for this value.


Solution

  • It's just matter of number representation. You just have to use correct data types to print or use:

    Version 1: int8_t data = EEPROM.read(addr);

    Version 2:

    byte data = EEPROM.read(addr);
    Serial.print((int8_t)data);
    

    EEPROM.write can be used directly with int8_t: EEPROM.write(int8_value);

    Or, if you wan't int, put/get methods can be used for it (even for structs containing POD types only or so)