Store number over 1 byte in EEPROM

frank0
Posts: 4
Joined: Wed Mar 20, 2024 10:49 am

Store number over 1 byte in EEPROM

Postby frank0 » Wed Mar 20, 2024 10:53 am

New to this, trying to store a persistent number between boots but it rolls over after 8 bits. Works as expected until I hit 256. Is each address only capable of holding a byte? How do I abstract that away to store larger numbers?

Code: Select all

#include <EEPROM.h>
#define EEPROM_SIZE 512

int numClick = 0;
in setup()

Code: Select all

EEPROM.begin(EEPROM_SIZE);
numClick = EEPROM.read(0);
in loop() on certain condition

Code: Select all

numClick = EEPROM.read(0);
........
numClick++;
........
EEPROM.write(0, numClick);
EEPROM.commit();

ESP_Sprite
Posts: 9764
Joined: Thu Nov 26, 2015 4:08 am

Re: Store number over 1 byte in EEPROM

Postby ESP_Sprite » Thu Mar 21, 2024 3:22 am

Yeah, the EEPROM library emulates an actual EEPROM device which stores an array of bytes. If you want to store larger numbers, you'd need to split it into multiple bytes. A better option is to use the Preferences library, which is more flexible as it doesn't have to emulate a hardware device.

lbernstone
Posts: 829
Joined: Mon Jul 22, 2019 3:20 pm

Re: Store number over 1 byte in EEPROM

Postby lbernstone » Thu Mar 21, 2024 4:33 am

While I completely agree with Sprite that Preferences is preferred (haha), there are shorthand functions in the EEPROM library to make it easier to deal with larger numbers. You do still have to keep track of how many bytes you are using so you can read/write to the correct addresses. See the extra example

frank0
Posts: 4
Joined: Wed Mar 20, 2024 10:49 am

Re: Store number over 1 byte in EEPROM

Postby frank0 » Sun Apr 07, 2024 1:39 pm

Thank you both for the info, all working well now with preferences instead :)

Who is online

Users browsing this forum: m8nix70 and 103 guests