View previous topic :: View next topic |
Author |
Message |
joshkeys
Joined: 16 Aug 2005 Posts: 37 Location: Fredericton,NB
|
transmitting a floating point number using i2c |
Posted: Thu Aug 18, 2005 8:08 am |
|
|
Has anyone tried this before? It seems to me that if you try to do this it will convert it to an 8 bit int before transmission.. Any suggestions or way around this without 1000 lines of code?
Josh |
|
|
Ttelmah Guest
|
|
Posted: Thu Aug 18, 2005 8:24 am |
|
|
The easiest way to my mind, is to take advantage of a union.
If you have:
Code: |
union float_bytes {
float fval;
int8 b[4];
} value;
int8 ctr;
value.fval = your_foating_point_number;
for (ctr=0;ctr<4;ctr++) {
send_how_you_want(value.b[ctr]);
}
|
This allows you to access the four bytes comprising the float, as 'value.b[0] ... value.b[3]', and send these however you want (I2C, serial etc.).
Then when retrieving the data, the same trick is used in reverse, writing the individual bytes into value.b[ctr], and then when all four bytes are retrieved, value.fval, contains the complete number. :-)
Best Wishes |
|
|
joshkeys
Joined: 16 Aug 2005 Posts: 37 Location: Fredericton,NB
|
|
Posted: Thu Aug 18, 2005 8:27 am |
|
|
So this takes only the exact binary representation instead of converting it to a type? I am going to give it a try. Thanks
Josh |
|
|
joshkeys
Joined: 16 Aug 2005 Posts: 37 Location: Fredericton,NB
|
|
Posted: Thu Aug 18, 2005 8:31 am |
|
|
Code: |
union float_bytes {
float fval;
int8 b[4];
} value;
int8 ctr;
value.fval = your_foating_point_number;
for (ctr=0;ctr<4;ctr++) {
send_how_you_want(value.b[ctr]);
}
|
I see that after union float_bytes there is an opening brace which closes before value. what is value? a float or what? there is no info on this union function in ccs so im not familiar with it. sorry.
Thanks
Josh |
|
|
Mark
Joined: 07 Sep 2003 Posts: 2838 Location: Atlanta, GA
|
|
Posted: Thu Aug 18, 2005 8:53 am |
|
|
A union is not a CCS function. Its a part of the C language. It is a way of overlapping variables in memory which gives you different ways to access them. |
|
|
Ttelmah Guest
|
|
Posted: Thu Aug 18, 2005 9:54 am |
|
|
As Mark says, a union is a type declaration, just like a 'structure'. It is in the manual, under 'data types'. It does not declare anything itself, but allows multiple variables, to access the same memory area. So 'value.fval', is a floating point variable stored in the union, and 'value.b[n]', is an array of four bytes stored in exactly the same area. It is a generic part of C, and you should read up on how to use it, but provides a really convenient way to access parts of a larger variable. :-)
Best Wishes |
|
|
|