#include <EEPROM.h>
#define EEPROM_SIZE 512 // Adjust the size as per your requirement
void setup() {
Serial.begin(115200);
while (!Serial) {
delay(10);
}
String textToSave;
// Prompt user to enter a string
Serial.println("Enter a string to save in EEPROM:");
// Wait for user input
while (!Serial.available()) {
delay(10);
}
// Read the string from Serial Monitor
while (Serial.available()) {
char c = Serial.read();
if (c == '\n' || c == '\r') { // Check for newline or carriage return
break;
}
textToSave += c;
}
// Read the existing string from EEPROM
String storedText = readStringFromEEPROM(0);
// Check if the new string differs from the existing one
if (textToSave != storedText) {
// Save the string to the EEPROM only if it's different
saveStringToEEPROM(0, textToSave);
Serial.println("String saved in EEPROM.");
} else {
Serial.println("String is the same as the previous one in EEPROM.");
}
// Read and display the stored string from the EEPROM
storedText = readStringFromEEPROM(0);
Serial.print("Stored Text in EEPROM: ");
Serial.println(storedText);
}
void loop() {
// Your main code here
}
void saveStringToEEPROM(int address, String data) {
EEPROM.begin(EEPROM_SIZE); // Begin EEPROM
for (unsigned int i = 0; i < data.length(); i++) {
if (EEPROM.read(address + i) != data[i]) {
EEPROM.write(address + i, data[i]);
}
}
if (EEPROM.read(address + data.length()) != '\0') {
EEPROM.write(address + data.length(), '\0'); // Null-terminate the string
}
EEPROM.commit(); // Commit changes
EEPROM.end(); // End EEPROM
}
String readStringFromEEPROM(int address) {
EEPROM.begin(EEPROM_SIZE); // Begin EEPROM
char charRead = EEPROM.read(address);
String readString = "";
while (charRead != '\0' && address < EEPROM_SIZE) {
readString += charRead;
address++;
charRead = EEPROM.read(address);
}
EEPROM.end(); // End EEPROM
return readString;
}