Hi all,
i'm a newbie to arduino.
How to convert 2 bytes of uint16 to float32 value.
These values i'll be receiving from my modbus device.
thanks
Hi all,
i'm a newbie to arduino.
How to convert 2 bytes of uint16 to float32 value.
These values i'll be receiving from my modbus device.
thanks
The compiler does that for you.
unsigned int x;
float f;
x = 432;
f = x;
// Sometimes you want to force the compiler to convert the types.
// But that is not needed in this example.
f = (float) x;
if it is used e.g. as a parameter for a function you can also multiply * 1.0
unsigned int x = 355;
float f = sqrt(x*1.0);
The other way around is not always possible as
Hello,
From my meter i'm receiving two uint16 values which combine to make a float32 value.
a=13667;
b=17992;
in python i used struct.pack and struct.unpack to get float values.
First i packed the int values to Hex and then unpacked it to float. But i used to specify endian also.
How to do this operation in arduino Leonardo.
// untested example
union
{
uint16_t u[2];
float f;
} meterdata;
meterdata.u[0] = a;
meterdata.u[1] = b;
Serial.println( meterdata.f);
Hello Erdin,
Thanks for the reply.
The data converted is for little endian.
How to do it for big endian.
The data converted for little endian is correct.
Do you know what a union is ?
Every item occupies the same memory location. So the 4 bytes of the array are at the same memory location as the 4 bytes of the float.
To change them, you could do this
...
meterdata.u[0] = b;
meterdata.u[1] = a;
...
This was an example with a union.
It is also possible to do it directly in the memory location of a float variable, or with a unsigned long in between the conversion.
I'm not 100% sure about your data. Are the uint16 variables the 16 upper and 16 lower bits of a floating point variable ? So the actual integer value of those uint16 has no meaning ?