1

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!

  • 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. – Edgar Bonet Apr 5 '17 at 15:54
  • That did the trick. Appreciate it man! – Jon Goe Apr 5 '17 at 15:55
  • Also you only want one value to store the counter in, not two. Either a or value - take your pick. – Majenko Apr 5 '17 at 16:04
  • 2
    @MichelKeijzers: The EEPROM is rated for 100K write cycles. – Edgar Bonet Apr 5 '17 at 17:16
  • 2
    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 Apr 5 '17 at 17:35

Your Answer

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

Browse other questions tagged or ask your own question.