#include <EEPROM.h>
void setup() {
Serial.begin(9600);
/*
eeprom_fillRandom();
EEPROM.write(1000, '|');
eeprom_printContent();
Serial.println();
Serial.println(eeprom_findLastCharIndex('|'));
*/
eeprom_printContentRAW();
Serial.println("");
eeprom_write(0, "I have a dental pain for an example.");
eeprom_printContentRAW();
Serial.println("");
eeprom_writeStringToLowestAvailableAddress("And here it continues");
eeprom_printContentRAW();
Serial.println("");
}
void loop() {
// put your main code here, to run repeatedly:
}
void eeprom_fillWithFF() {
for (int i = 0; i < EEPROM.length(); i++) {
EEPROM.write(i, 0xFF);
}
}
void eeprom_fillRandom() {
Serial.print("Filling an EEPROM with random characters... ");
randomSeed(analogRead(0)); // Seed the random number generator with a random value from the analog input
for (int i = 0; i < EEPROM.length(); i++) {
char c;
if (i % 3 == 0) {
c = '0' + random(10); // Generate a random digit
} else if (i % 3 == 1) {
c = 'A' + random(26); // Generate a random uppercase letter
} else {
c = 'a' + random(26); // Generate a random lowercase letter
}
EEPROM.write(i, c); // Write the character to the current address in EEPROM
}
Serial.println("Done.");
}
void eeprom_printContent() {
for (int i = 0; i < EEPROM.length(); i++) {
byte data = EEPROM.read(i);
if (i % 16 == 0) { // group output by 8 characters per line
Serial.println();
//Serial.print(i);
char buf[5];
sprintf(buf, "%04d", i);
Serial.print(buf);
Serial.print(" :");
}
if (i % 8 == 0) {
Serial.print(" ");
}
Serial.print((char)data);
}
}
void eeprom_printContentRAW() {
for (int i = 0; i < EEPROM.length(); i++) {
byte data = EEPROM.read(i);
Serial.print((char)data);
}
}
void eeprom_printContentHEX() {
for (int i = 0; i < EEPROM.length(); i++) {
byte data = EEPROM.read(i);
if (i % 16 == 0) { // group output by 16 bytes per line
Serial.println();
char buf[5];
sprintf(buf, "%04d", i);
Serial.print(buf);
Serial.print(" :");
}
if (i % 8 == 0) {
Serial.print(" ");
}
Serial.print(data < 16 ? "0" : ""); // pad with leading zero if necessary
Serial.print(data, HEX);
Serial.print(" ");
}
}
int eeprom_findLastCharIndex(char c) {
int last_index = -1;
for (int i = 0; i < EEPROM.length(); i++) {
if (EEPROM.read(i) == (int)c) {
last_index = i;
}
}
return last_index;
}
void eeprom_write(unsigned int address, const char* data) {
int dataSize = strlen(data); // size of the data array
// write the data to the EEPROM
for (int i = 0; i < dataSize; i++) {
EEPROM.write(address + i, data[i]);
}
}
void eeprom_writeStringToLowestAvailableAddress(const char* data) {
int dataSize = strlen(data); // size of the data array
// find the lowest available address
int lowestAddr = -1;
for (int i = 0; i < EEPROM.length(); i++) {
if (EEPROM.read(i) == 0xFF) {
lowestAddr = i;
break;
}
}
if (lowestAddr != -1) { // if a free address was found
// write the data to the EEPROM
for (int i = 0; i < dataSize; i++) {
EEPROM.write(lowestAddr + i, data[i]);
}
}
}