View previous topic :: View next topic |
Author |
Message |
assaad
Joined: 09 Dec 2009 Posts: 37
|
floating numbers problem with saving and reloading |
Posted: Fri Jun 10, 2011 8:55 am |
|
|
Hi everyone ;
I have problem with saving and reloading floating points with CCS v4.106
I am saving data in external Static RAM as 4 bytes and when i read it back i get a problem of 0.01 changing and that sometimes happened and sometimes does not !
for example I save the float : 0.5 when I read it I get 0.49; and that happened about 50% of the readings so 50% i get the correct value;
Is there any solution for this issue ?
Thank you |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19537
|
|
Posted: Fri Jun 10, 2011 2:38 pm |
|
|
Have you tested that the number is what you expect before saving?.
Provided your storage is working right, and you are performing the transfer right, saving and restoring the data will make no difference at all. You need to remember though that FP numbers do _not_ represent numbers accurately. 0.5 ought to be right, but for most numbers there will be rounding errors. So (for example), if you store 0.614, the FP number stored will convert 'back' as 0.61400002.
How are you extracting the bytes to store them?. Code like:
Code: |
union {
int8 bytes[4];
float fpval;
} val;
//Then val.fpval is the float, and val,bytes[0] to val.bytes[3] are the bytes
|
Or using a pointer, and casting it to point to an int8, are the safest ways of transferring the data.
I'd suspect the numbers are wrong before the transfer. 0.5, and 0.49, have very different byte values. The former is 0000007E, while the latter is 48E17A7D.
Best Wishes |
|
|
assaad
Joined: 09 Dec 2009 Posts: 37
|
|
Posted: Wed Jun 15, 2011 7:10 am |
|
|
Sorry for the late reply.
Here the routines that I use for saving and loading, I use pointers.
Code: |
void Write_Float_ram_low(int16 address1, float data1)
{
int8 i;
for(i = 0; i < 4; ++i)
{
ram_write_low(address1 + i, *((int8 *)(&data1) + i));
}
}
//------------
float Read_Float_ram_low(int16 address1)
{
int8 i;
float data1;
for(i = 0; i <4; ++i)
{
*((int8 *)(&data1) + i) = ram_read_low(address1 + i);
}
return data1;
} |
|
|
|
assaad
Joined: 09 Dec 2009 Posts: 37
|
|
Posted: Thu Jun 16, 2011 12:25 pm |
|
|
Any idea about this issue? |
|
|
PCM programmer
Joined: 06 Sep 2003 Posts: 21708
|
|
Posted: Thu Jun 16, 2011 1:20 pm |
|
|
Post your small test program that calls those routines, and demonstrates
the problem. Use printf statements to display the variables before you
save them, and after you read them.
Show us an example of how you get the .01 error.
Tell us the manufacturer and part number of the static ram.
Post all #include, #fuses, #use statements, and variable declarations
so we can compile the program without errors.
Make it be as short as possible. Here's an example:
http://www.ccsinfo.com/forum/viewtopic.php?t=32722&start=3
Preferably, make the code in main() in your program be even shorter than that. |
|
|
|