0

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.

Edgar Bonet
  • 45,094
  • 4
  • 42
  • 81

1 Answers1

0

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); }

Edgar Bonet
  • 45,094
  • 4
  • 42
  • 81