Storing Strings in EEPROM from Serial Input Example

Here is a short example demonstrating taking serial string input and storing and retrieving to and from EEPROM. This is done using EEMEM and <avr.eeprom.h>. I also demonstrate using PSTR-like functionality to keep serial response strings in flash but "print" them to serial directly, without copying them into a temp array using PROGMEM.

For brevity and laziness, I define three separate EEMEM strings and select them via a case statement. I am not sure though EEMEM will handle the pointer to pointer setup you'd need to fetch the start address of the char array inside another array. Anyone try it? Also, I have seen many examples using structs. I should try that too, but held off since I have to look into whether you have to copy the whole thing into RAM or can just copy a specific member of the struct.

Here's the code: (it wouldn't fit here)

I hope this is helpful. Comments are appreciated.

You've declared EEPROM_BYTES as 1024, but a 168 has only 512 bytes of EEPROM, and a MEGA2560 has 4096 bytes.
This would be better defined this value using one of the processor-specific predefines

Thanks for the reply. I've never used predefines but here's an example:

CPU Type and How to Determine Arduino Bord

According to selected target processor, compiler defined constant by processor name.
Constant CPU Board
AVR_ATmega168 ATmega 168 Arduino Decimilia and older
AVR_ATmega328P ATmega 328P Arduino Duemilanove and Uno
AVR_ATmega1280 ATmega 1280 Arduino Mega
AVR_ATmega2560 ATmega 2560 Arduino Mega 2560

So by testing of these constants you can determine board type. For example:

#if not (defined(AVR_ATmega2560) || defined(AVR_ATmega1280))
#error Sorry dude, this program works only on Arduino Mega


#define EEPROM_BYTES 1024

#define EEPROM_BYTES (E2END+1)

Problem solved.

Further thoughts on storing data in EEPROM as a struct...

The example given here:

is pretty good in that it uses <avr/eeprom.h> and does not require you to reference a memory address when storing/retrieving data. The downside is that you have to copy the whole struct from EEPROM into RAM, which isn't so good for storing and retrieving strings. There must be a way to dereference one value at a time from EEPROM into RAM though.