I have been looking for a way to save signed long numbers into the arduino's eeprom.
My initial idea was to use simple math to break it into separate bytes and then feed them to eeprom one by one.
Although it will probably work, I don t know how efficient this would be.
Any suggestions on doing this in a more graceful way?
The interface to the EEPROM is byte-wide, so yes, you're going to have to break down the values.
Different ways of doing this include casting byte pointers to the address of the variable you want to write, or use a union.
Or, as you say, simple shift and mask.
that is beyond me. it should obvious work, but because there are no comments in the code, i have no idea what is happening. i can code plain c, but this seems to be c++.
another reason to start studying c++. this seems to be a good example. but for now i have to find another plain c way to write and read a int to eeprom.
but i have'nt tested it yet. the reference is not clear about the functionality of the typecast to byte. i assume (i know, dangerous!) that it takes the lower byte of the int, but i have to find out in debugging.
got a nice quote from a friend of mine about c++:
"If C gives you enough rope to hang yourself, then C++ gives you enough rope to bind and gag your neighborhood, rig the sails on a small ship, and still have enough rope to hang yourself from the yardarm"
to those like me who wish to read and write long integers to EEPROM without using pointers.
// read double word from EEPROM, give starting address
unsigned long EEPROM_readlong(int address) {
//use word read function for reading upper part
unsigned long dword = EEPROM_readint(address);
//shift read word up
dword = dword << 16;
// read lower word from EEPROM and OR it into double word
dword = dword | EEPROM_readint(address+2);
return dword;
}
//write word to EEPROM
void EEPROM_writeint(int address, int value) {
EEPROM.write(address,highByte(value));
EEPROM.write(address+1 ,lowByte(value));
}
//write long integer into EEPROM
void EEPROM_writelong(int address, unsigned long value) {
//truncate upper part and write lower part into EEPROM
EEPROM_writeint(address+2, word(value));
//shift upper part down
value = value >> 16;
//truncate and write
EEPROM_writeint(address, word(value));
}
unsigned int EEPROM_readint(int address) {
unsigned int word = word(EEPROM.read(address), EEPROM.read(address+1));
return word;
}