I am trying to save and retrieve doubles from the EEPROM memory, using the code below:
#include <EEPROM.h>
void setup(){
Serial.begin(9600);
Serial.println("Arduino has reset");
double x = 13426.8888;
Serial.print(x);
Serial.println(" is about to be saved");
saveDouble(x,0);
delay(500);
double y = loadDouble(0);
Serial.print(y);
Serial.println(" has been loaded");
int a = 456;
Serial.print(a);
Serial.println(" is about to be saved");
saveInt(a,5);
delay(500);
int b = loadInt(5);
Serial.print(b);
Serial.println(" has been loaded");
}
void loop(){
}
int saveDouble(double toSave, int firstByte){
char buffer[sizeof(double)];
memcpy(&buffer,&toSave,sizeof(double));
for (int i=0; i<sizeof(double); i++) {
EEPROM.write(firstByte+i,buffer[i]);
}
return 1;
}
int loadDouble(int firstByte){
char buffer[sizeof(double)];
double loaded;
for (int i = 0; i<sizeof(double);i++) {
Serial.println(i);
buffer[i] = EEPROM.read(i+firstByte);
}
memcpy(&loaded,&buffer,sizeof(double));
return loaded;
}
int saveInt(int toSave, int firstByte){
char buffer[sizeof(int)];
memcpy(&buffer,&toSave,sizeof(int));
for (int i=0; i<sizeof(int); i++) {
EEPROM.write(firstByte+i,buffer[i]);
}
return 1;
}
int loadInt(int firstByte){
char buffer[sizeof(int)];
int loaded;
for (int i = 0; i<sizeof(int);i++) {
buffer[i] = EEPROM.read(i+firstByte);
}
memcpy(&loaded,&buffer,sizeof(int));
return loaded;
}
At first I thought it was working, but then I changed the code to have doubles with decimal parts. Then the code only returns the whole part of the number.
I have managed to save using a different method (pointers and shizzle) but I am intrigued as to why this doesn't work, and why I am getting the whole number results. I assume I am missing a byte somewhere, but I cannot see how I can be.
Anyway, thanks in advance for any help.