Hardware Reference
In-Depth Information
the right by a certain number of bits. Masking makes it possible to perform bit-
wise operations on a portion of a binary number. Take the following example:
void EEPROMWriteInt(int address, int value)
{
byte lowByte = ((value >> 0) & 0xFF);
// Now shift the binary number 8 bits to the right
byte highByte = ((value >> 8) & 0xFF);
EEPROM.write(address, lowByte);
EEPROM.write(address + 1, highByte);
}
In this example, an int is to be saved into EEPROM. It contains two bytes:
the low byte and the high byte. The terminology “low” and “high” bytes is
used when a number is stored on several bytes; the low byte contains the least
signii cant part of the number, and the high byte contains the most signii cant
part of the number. First, the lowest byte is extracted. It simply takes the num-
ber and performs a bitwise AND with 0xFF . The 0x in front of the letters tells the
Arduino IDE that this is a hexadecimal number. Just like binary, hexadecimal is
another way of printing a number. Instead of using only two values per i gure,
hexadecimal uses 16. 0xFF is the hexadecimal representation of 255, the largest
number that a byte can hold. Then, the same value is shifted right 8 bits, and
again, an AND is performed. This is an elegant solution that can work for integers
but will not work for more complex numbers, like a l oating-point. You cannot
perform shifts with a l oating-point, more advanced techniques are required.
Several users have requested EEPROM functions to write any sort of data, one
possible solution is available in the Arduino Playground and is called EEPROM
Write Anything. If you want to write anything to EEPROM, look at this example
from the playground—but be forewarned, it uses advanced programming
techniques that are not covered in this topic:
http://playground.arduino.cc/Code/EEPROMWriteAnything
Here is an extract of this code:
template <class T> int EEPROM_writeAnything(int ee, const T& value)
{
const byte* p = (const byte*)(const void*)&value;
unsigned int i;
for (i = 0; i < sizeof(value); i++)
EEPROM.write(ee++, *p++);
return i;
}
Again, this code requires specii c information: the exact size of the value to
save. Be careful when using int values; again, on the Arduino Due, they are a
different size than other Arduino boards.
Search WWH ::




Custom Search