View previous topic :: View next topic |
Author |
Message |
evsource
Joined: 21 Nov 2006 Posts: 129
|
Weird result with read and write float to EEPROM |
Posted: Mon Apr 09, 2007 6:13 am |
|
|
I've really bashed my head around trying to figure out why the following code doesn't work.
The value "130.0" is output to the screen when I expect "14.4". Can someone verify that this does/doesn't work for them, or if the solution is obvious?
By the way, I included a write to the EEPROM with an integer value just to show that writing to the EEPROM is working correctly. The value "55" is printed to the screen.
Code: | #include <18f2520.h>
#device *=16
#fuses HS,NOWDT,NOPROTECT
#use delay(clock=8000000)
#use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7, errors)
#define EEP_INT_LOCATION 0x08
#define EEP_FLOAT_LOCATION 0x09
void write_float_eep(BYTE starting_address, float data) {
int k;
for (k=0;k<4;k++)
write_eeprom(starting_address+k,*(&data + k));
}
float read_float_eep(BYTE starting_address) {
float temp;
int k;
for(k=0;k<4;k++)
*(&temp + k) = read_eeprom(starting_address + k);
return temp;
}
void main() {
float set_value_float;
float read_value_float;
int set_value_int;
int read_value_int;
set_value_float = 14.4;
set_value_int = 55;
write_float_eep( EEP_FLOAT_LOCATION, set_value_float );
write_eeprom( EEP_INT_LOCATION, set_value_int );
read_value_float = read_float_eep( EEP_FLOAT_LOCATION );
read_value_int = read_eeprom( EEP_INT_LOCATION );
while(TRUE) {
printf( "\r\nRead float value: %4.1f\r\nRead int value: %u",read_value_float, read_value_int );
delay_ms( 5000 );
}
} |
|
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
|
evsource
Joined: 21 Nov 2006 Posts: 129
|
|
Posted: Mon Apr 09, 2007 9:24 am |
|
|
Wow, thanks for the response. That was the answer. I'm using v4.030 of the PCH compiler.
Why would the casting to int8* be necessary now and not before 4.021?
I love this forum. Thanks again! |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Mon Apr 09, 2007 12:27 pm |
|
|
It's because in the past CCS didn't follow the standard. But they fixed
it, starting with vs. 4.021. See this article on C pointers in Wikipedia.
http://en.wikipedia.org/wiki/C_(programming_language)#pointers
It says:
Quote: | Pointer arithmetic is automatically scaled by the size of the pointed-to data type. |
Therefore, if you want to access the individual bytes of a float, you must
cast the pointer to a byte-pointer. That's what the new code in the FAQ
does. Before vs. 4.021, the "address of" operator always returned a
byte pointer. |
|
|
|