How to convert from HEX to Floating point in Arduino IDE

Asked by sajid zaman

hi,
     is there any function which convert HEX data array to floating point as i am communicating two Arduino the one is collection data from FreeIMU and send to another Arduino which will convert the hex data stream to floating point (quaternion example).thanks

Question information

Language:
English Edit question
Status:
Solved
For:
FreeIMU Edit question
Assignee:
No assignee Edit question
Solved by:
Fabio Varesano
Solved:
Last query:
Last reply:
Revision history for this message
Best Fabio Varesano (fabio-varesano) said :
#1

There is not such fuction. But, when doing Arduino to Arduino communication, you'd better using directly raw bytes instead of HEX..

This is some example code:

Write float over serial:
byte * f_p = (byte *) &float_var;
Serial.write(f_p[0]);
Serial.write(f_p[1]);
Serial.write(f_p[2]);
Serial.write(f_p[3]);

Read back from serial:
float float_var;
byte * f_p = (byte *) &float_var;
f_p[0] = Serial.read();
f_p[1] = Serial.read();
f_p[2] = Serial.read();
f_p[3] = Serial.read();

Not tested, but should give you the idea.

Revision history for this message
sajid zaman (engr-sajidzaman) said :
#2

thanks for reply, this works fine but giving me only up to 2 digits after point e.g if i sending float=-0.687564 at transmitter then the receiver receive it as up-to only 2 digits after point i-e float=-0.68 at receiver end.

Revision history for this message
Fabio Varesano (fabio-varesano) said :
#3

Serial.print for float variables in Arduino only prints 2 digits after the dot. So 5.567 becomes 5.57.
But, the received data should be fine. As a test you can print the float variable normally and then multiplied by 100..
so, 5.567 would be printed as 5.57 but if you multiply for 100 .. it will be printed as 556.70..

Revision history for this message
sajid zaman (engr-sajidzaman) said :
#4

oohhhh!! i for got this point,i wrote Serial.print(floatvar,8) and it show me complete float value, thanks a lot

Revision history for this message
sajid zaman (engr-sajidzaman) said :
#5

Thanks Fabio Varesano, that solved my question.