I am working on an arduino (based off the AVR platform) and I have a method that takes in a float and writes it to EEPROM. I have to convert the float to a byte array to interact with EEPROM. I have two functions as follow:
void WriteFloatToEEPROM(int address, float value) {
union {
byte byteVal[4];
float floatVal;
} data;
data.floatVal = value;
for (int i = 0; i < 4; i++) {
EEPROM.update(address + i, data.byteVal[i]);
}
}
float ReadFloatFromEEPROM(int address) {
union {
byte byteVal[4];
float floatVal;
} data;
for (int i = 0; i < 4; i++) {
uint8_t readValue = EEPROM.read(address + i);
data.byteVal[i] = readValue;
}
return data.floatVal;
}
When I print out the results of this I get the following as a few examples:
Read value at address 50 for float read 0
Read value at address 51 for float read 0
Read value at address 52 for float read 0
Read value at address 53 for float read 0
Returned float val for address 50:0.00
Read value at address 90 for float read 0
Read value at address 91 for float read 0
Read value at address 92 for float read 0
Read value at address 93 for float read 160
Returned float val for address 90:-0.00
Read value at address 130 for float read 44
Read value at address 131 for float read 113
Read value at address 132 for float read 61
Read value at address 133 for float read 138
Returned float val for address 130:-0.00
Read value at address 170 for float read 0
Read value at address 171 for float read 0
Read value at address 172 for float read 0
Read value at address 173 for float read 0
Returned float val for address 170:0.00
Am I using a union wrong/writing to EEPROM backwards or something? Also if anyone has a better way of doing this, I am open to suggestions. Thanks in advance