#include <EEPROM.h>
#define RESTART_COUNT_ADDR 0 // Address in EEPROM for restart count
void setup() {
Serial.begin(9600);
while (!Serial);
Serial.println("EEPROM-Based Microcontroller Restart Counter");
// Increment and read the restart counter
int restartCount;
EEPROM.get(RESTART_COUNT_ADDR, restartCount);
restartCount++;
EEPROM.put(RESTART_COUNT_ADDR, restartCount);
Serial.print("Microcontroller restarted ");
Serial.print(restartCount);
Serial.println(" times.");
// Provide option to reset the counter
Serial.println("Do you want to reset the counter. Press Y or N");
while(1)
{
if (Serial.available()) {
char input = Serial.read();
if (input == 'Y' || input == 'y') {
Serial.println("Resetting restart counter...");
EEPROM.put(RESTART_COUNT_ADDR, 0);
Serial.println("Restart counter reset. Please restart the microcontroller.");
break;
}
else{
Serial.println("Counter not resetted");
break;
}
}
}
}
void loop() {
Serial.println("Doing some task.......");
delay(5000);
}
Read, Increment, and Store Restart Count:
EEPROM.get()
to read the current value from the defined address. EEPROM.put().
int restartCount;
EEPROM.get(RESTART_COUNT_ADDR, restartCount); // Read current value
restartCount++;
EEPROM.put(RESTART_COUNT_ADDR, restartCount); // Write updated value
Serial.print("Microcontroller restarted ");
Serial.print(restartCount);
Serial.println(" times.");
User Option to Reset Counter:
Serial.println("Do you want to reset the counter? Press Y or N");
while (1) {
if (Serial.available()) {
char input = Serial.read();
if (input == 'Y' || input == 'y') {
Serial.println("Resetting restart counter...");
EEPROM.put(RESTART_COUNT_ADDR, 0); // Reset counter
Serial.println("Restart counter reset. Please restart the microcontroller.");
break;
} else {
Serial.println("Counter not reset.");
break;
}
}
}
Keep in mind the limited write cycle with the EEPROM cell.
Also, it is advisable to reset the EEPROM beforehand.