#include <EEPROM.h>
#include <Wire.h> // Library for I2C communication
#include <LiquidCrystal_I2C.h> // Library for LCD
LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 20, 4); // Change to (0x27,20,4) for 20x4 LCD.
const unsigned int MAX_MESSAGE_LENGTH = 12;
void writeStringToEEPROM(int addrOffset, const String &strToWrite)
{
byte len = strToWrite.length();
EEPROM.write(addrOffset, len);
for (int i = 0; i < len; i++)
{
EEPROM.write(addrOffset + 1 + i, strToWrite[i]);
}
}
String readStringFromEEPROM(int addrOffset)
{
int newStrLen = EEPROM.read(addrOffset);
char data[newStrLen + 1];
for (int i = 0; i < newStrLen; i++)
{
data[i] = EEPROM.read(addrOffset + 1 + i);
}
data[newStrLen] = '\0'; // !!! NOTE !!! Remove the space between the slash "/" and "0" (I've added a space because otherwise there is a display bug)
return String(data);
}
void setup() {
Serial.begin(9600);
lcd.init();
lcd.backlight();
lcd.clear();
}
void loop() {
//Check to see if anything is available in the serial receive buffer
while (Serial.available() > 0)
{
//Create a place to hold the incoming message
static char message[MAX_MESSAGE_LENGTH];
static unsigned int message_pos = 0;
//Read the next available byte in the serial receive buffer
char inByte = Serial.read();
//Message coming in (check not terminating character) and guard for over message size
if ( inByte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1) )
{
//Add the incoming byte to our message
message[message_pos] = inByte;
message_pos++;
}
//Full message received...
else
{
//Add null character to string
message[message_pos] = '\0';
//Print the message (or do other things)
Serial.println(message);
writeStringToEEPROM(10, message);
String retrievedString = readStringFromEEPROM(10);
Serial.print("The String we read from EEPROM:");
Serial.println(retrievedString);
lcd.setCursor(0, 0); // Set the cursor on the third column and first row.
lcd.print(retrievedString); // Print the string "Hello World!"
//Reset for the next message
message_pos = 0;
}
}
}