I am from Argentina.
I am making a kind of project for my car, and one of the many functions I am planning, is to check how many times the Arudino has been powered up.
I was thinking of a simple counter and save it to the EEPROM (within setup()
).
I was able to save the value, and read it, but I cannot add +1 to that value stored in the EEPROM.
#include <EEPROM.h>
char buffer[15]; // length of the variable, character count
int cant;
void setup()
{
Serial.begin(9600);
Serial.println("Write to EEPROM: ");
EEPROM.put(0, "12345678901234");
Serial.print("Read from EEPROM1: ");
Serial.println(EEPROM.get(0, buffer));
Serial.print("Read from EEPROM2: ");
Serial.println(buffer);
Serial.print("Read from EEPROM3: ");
cant=(EEPROM.get(0, buffer));
Serial.println(cant);
}
void loop()
{
}
And I am getting as output:
Write to EEPROM:
Read from EEPROM1: 12345678901234
Read from EEPROM2: 12345678901234
Read from EEPROM3: 370
The variable cant
is showing a different value.
-
use an external memory device ... arduino.stackexchange.com/questions/226/… ... a FRAM device has a longer life ... duckduckgo.com/?q=memory+fram+i2c&ia=webjsotola– jsotola2025年01月15日 16:20:54 +00:00Commented Jan 15 at 16:20
1 Answer 1
The call EEPROM.get(0, buffer)
correctly reads the EEPROM data into
the provided buffer. It returns, for convenience, a reference to that
buffer. This being a reference to an array, it decays to a pointer to
its first element, which is a pointer of type char *
. The line
cant=(EEPROM.get(0, buffer));
is thus implicitly converting this pointer to an integer. The value you
get is the memory address of the buffer
array. Probably not what you
are interested in.
If you want to store a counter in the EEPROM, there is no point in
storing it as text. Store it as a plain binary number. I suggest to use
the type long
(or unsigned long
), just in case you power up your car
more than 65,535 times:
void setup()
{
Serial.begin(9600);
long power_up_count;
// Get the power-up count from the EEPROM.
EEPROM.get(0, power_up_count);
Serial.print("Old power up count = ");
Serial.println(power_up_count);
// Increment it.
EEPROM.put(0, power_up_count + 1);
// Verification: read it back.
EEPROM.get(0, power_up_count);
Serial.print("New power up count = ");
Serial.println(power_up_count);
}
-
You are a genius!!!!!!!! Thanks very much Edgar! So, if i use char buffer[15]; i am writing a string, aka text?Diego Nunez– Diego Nunez2025年01月15日 21:18:42 +00:00Commented Jan 15 at 21:18
-
@DiegoNunez: Although an array of
char
is typically used for holding text, you could in principle put whatever you want there. What makes it text is what you put inside. For instance,"12345678901234"
is text.Edgar Bonet– Edgar Bonet2025年01月15日 21:53:04 +00:00Commented Jan 15 at 21:53