I have newtek meter which gives 9 bytes of data and 4,5,6,7 bytes are important they are in ieee747 format so how can I convert this byte array into floating point number?
int incoming[9];
int byte_array[4];
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(3,OUTPUT);
}
int i=0;String u;
long speedLong;
void loop() {
byte message[] = {0x01,0x04,0x00,0x46,0x00,0x02,0x90,0x1E}; //byte array to read frequency value from meter
Serial.write(message,sizeof(message));
delay(1000);
int z=Serial.available();
Serial.println("Incoming bytes are:");
Serial.println(z);
while (Serial.available() > 0)
{
incoming[i] = Serial.read();
Serial.print(incoming[i]);
Serial.print('\t');
i++;
}
int j=0;
for(i=3;i<=6;i++) //sorting important byte array
{
Serial.println();
byte_array[j]=incoming[i];
Serial.print(byte_array[j]);
Serial.print('\t');
j++;
}
i=0;
Serial.println();
delay(2000);
}
The above code does the needful of getting the data and sorting the important bytes but, now I want to convert those improtant byte array into one floating point number which represents the parameter value how do i do that?
I did try both of them but,in both cases I am not getting expected values i will post the code with output here:
Now I am just trying out with sample code sending byte array :0x42,0x48,0x23,0x8A and this value comes out to be 50.32 using IEEE734 format but the value I got are disaster
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
union {
byte b[4];
float fval;
} u;
float velocity;
long speedLong;
void loop() {
byte incoming[4]={0X42,0X48,0X23,0X8A};
// put your main code here, to run repeatedly:
for(int i=0;i<=3;i++)
{
Serial.print(incoming[i],HEX); // prints the byte in hex
u.b[i] = incoming[i]; //using union
speedLong = (speedLong << 8) | incoming[i];
}
velocity = u.fval; //should give floating point value
Serial.println("Value got from method 1: ");
Serial.print('\t');
Serial.println(velocity);
Serial.println("Value got from method 2: ");
Serial.print('\t');
Serial.println(speedLong);
delay(200);
}
ouput:
4248238AValue got from method 1:
-0.00
Value got from method 2:
1112023946
And I have tried both the methods any suggestions how I could proceed?
oh.. I got it right finally!!!!!
instead of sending as: { 0X42,0X48,0X23,0X8A};
we must send:{0X8A,0X23,0X48,0X42};
worked like charm only using union but not using the other method
ddk1:
oh.. I got it right finally!!!!!
instead of sending as: { 0X42,0X48,0X23,0X8A};
we must send:{0X8A,0X23,0X48,0X42};
Yes, as you've found the float must be stored low byte first.
That "second method" is not anything close to what you want. It is not even casting it to a float, but rather to a long integer. All that will give you is the bit pattern of the float, but stuffed into a long integer, so don't expect it to make any sense.
If you want to have another way to do it then use the pointer typecast method.