3

I have made a program that increments a counter everytime the up button is pressed. I am trying to write this value to EEPROM, so that when I turn my board off and on again, the value before power off is shown on screen.

I wrote this code but the value doesn't seem to be written to EEPROM. The counter incrementation works fine.

#include <EEPROM.h>
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

int addr = 0;
byte value;

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0,0);
}

int a;  
void loop() {
  uint8_t buttons = lcd.readButtons();
  if (buttons) {

    lcd.clear();
    lcd.setCursor(0,0);

    if (buttons & BUTTON_UP) {
      a+= 1;
      EEPROM.write(addr, a);
      value = EEPROM.read(addr);
      lcd.print(value);
      delay(100);
    }
  }
}

Thanks for the help!

7
  • 1
    The only time you read the EEPROM is right after writing it, which is pointless. You need to EEPROM.read() in setup() if you want the value restored at boot time. Commented Apr 5, 2017 at 15:54
  • 1
    That did the trick. Appreciate it man!
    – Jon Goe
    Commented Apr 5, 2017 at 15:55
  • 1
    The EEPROM.read and EEPROM.write read and write only a single byte. You can use EEPROM.put and EEPROM.get to read and write an (unsigned) int or a (unsigned) long.
    – Jot
    Commented Apr 5, 2017 at 16:09
  • 3
    @MichelKeijzers: The EEPROM is rated for 100K write cycles. Commented Apr 5, 2017 at 17:16
  • 3
    My normal EEPROM method is to set a variable to the desired value, along with a timestamp variable. Reset the timestamp variable every time the button is pressed. Then when a certain time has elapsed since the last press write the value to EEPROM. That way if you press the button 50 times in quick succession you only get one write to EEPROM. A couple of seconds delay on the write works well.
    – Majenko
    Commented Apr 5, 2017 at 17:35

1 Answer 1

1

just add a = EEPROM.read(addr); in your setup also, you can remove byte value and use a you wrote to memory in the previous line

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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