🔍

Write and Read from Arduino/ESP’s EEPROM

Put this in the head of your main script!


#include <EEPROM.h>

#define EEPROM_ADDRESS 0x50
#define VALUE_ADDRESS 0x00

int highscore = 0;

void setup() {
  

initializeEEPROM();
  
 //Serial.begin(9600);

  // Read the value from EEPROM and print it
  highscore = readEEPROM();
}

// execute this for saving it to the memory!
// writeEEPROM(highscore);


// Function to read an integer value from EEPROM
int readEEPROM() {
  int value = EEPROM.read(VALUE_ADDRESS) << 8;
  value |= EEPROM.read(VALUE_ADDRESS + 1);
  return value;
}

// Function to write an integer value to EEPROM
void writeEEPROM(int value) {
  EEPROM.write(VALUE_ADDRESS, value >> 8);
  EEPROM.write(VALUE_ADDRESS + 1, value & 0xFF);
}

// Function to check if a value exists in EEPROM, if not, create a default value
void initializeEEPROM() {
  int value = readEEPROM();
  if (value == 0xFFFF) {  // Check if value is uninitialized (default value of EEPROM)
    value = 1;           // Set default value
    writeEEPROM(value);  // Write the default value to EEPROM
  }
}