Hardware Reference
In-Depth Information
Suppose you need to store a string, dei ned as such:
char myString[20];
You can also set a string to a specii c value when you declare it. Note that
while this array can contain up to 20 elements, not all of them have data.
char myString[20] = "Hello, world!";
You can store information in EEPROM like this:
int i;
for (i = 0; i < sizeof(myString); i++)
{
EEPROM.write(i, myString[i]);
}
This routine will write the contents of the string to EEPROM memory, one
byte at a time. Even if the string is only 5 bytes long, it will store the contents
of the entire array. That is, if you declare a char array of 20 elements and only
have valid data in the i rst 5 bytes, you'll still be writing 20 bytes to EEPROM.
You could make a more optimized routine that automatically stops when it
receives a null character: the end of a C string, but because this routine writes
to EEPROM memory that is not often (if ever) changed, there is no point to over-
complexifying the program. Reading a string is just as easy:
int i;
for (i = 0; i < sizeof(myString); i++)
{
myString[i] = EEPROM.read(i);
}
Again, the operation is the same; it will take 1 byte from EEPROM and place
it into the string, and repeat for each byte in the string.
Reading and Writing Other Values
If the EEPROM can only read and write bytes, how can you save the contents
of an integer or a l oating point number? At i rst it might seem impossible, but
remember that in computers, everything is just 1s and 0s. Even a l oating-point
number is written in memory as binary, it just occupies a larger number of bytes.
Just like with strings, it is possible to write just about anything in EEPROM
memory, by reading and writing 1 byte at a time.
Before beginning, you must know exactly what sort of data you need to read
and write. For example, on all Arduinos except the Due, an int is written as
2 bytes. By using techniques known as shifts and masks, it is possible to “extract”
bytes of data. Shifting takes a binary number and “shifts” data to the left or to
 
Search WWH ::




Custom Search