Hardware Reference
In-Depth Information
Listing 6-1 ( continued )
81
82 // Print out the user's age
83 Serial.print("Oh, you are ");
84 Serial.print(age);
85 Serial.println("?");
86 Serial.print("I am ");
87 Serial.print(millis());
88 Serial.println(" microseconds old. Well, my sketch is.");
89
90 // Now save this to EEPROM memory
91 EEPROM.write(EEPROM_AGEPOS, age);
92
93 // Since we have all the information we need, and it has been
94 //saved, write a control number to EEPROM
95 EEPROM.write(EEPROM_DATAPOS, EEPROM_CONTROL);
96 }
97
98 }
99
100 void loop()
101 {
102 // put your main code here, to run repeatedly:
103 }
So, what has changed? Well, the most visible change is that the code con-
cerning Arduino's ABC recital has been removed. This example concentrates
on something else.
On line 11, the user's age is now stored in an unsigned char . Originally
this was stored in an int , but this presents a problem for EEPROM memory.
Remember that in Chapter 4 you saw that int values stored from -32768 to 32767.
You won't need all those numbers; humans don't (yet) live that long, and in any
case, negative numbers aren't necessary. The problem isn't the range; it is the
size of the container. On most Arduinos, an int is coded on 2 bytes (in the Due
it occupies 4 bytes). If you release your program as open source, you will have
no way of knowing which Arduino will be used. In addition, an int for an age
is a bad idea; it isn't optimal. An unsigned char is always 1 byte and can handle
numbers from 0 all the way to 255. This will be easier to write to an EEPROM.
On line 21, the sketch reads data from the EEPROM. The exact location is
dei ned by EEPROM_DATAPOS . Of course, the function could have been called
directly with the number 0 (and this is exactly what the compiler is going to
do), but adding a #define makes the code more readable and also allows the
developer to change memory location without worrying about forgetting a call.
This makes everything neater. This sketch shows the persistence of nonvolatile
memory, and as such, it has to have a way of ignoring any data stored. To do
this, a “control” byte is allocated. The Arduino reads a value in the EEPROM. If it
receives the number 42, it presumes that the EEPROM contains valid information
Search WWH ::




Custom Search