Arduino Mega2560 64bit double from modbus TCP registers

How Can i read an 64 bit double from 4 modbus
integer registers in arduino mega2560 ?

integer variables
1 = 16754
2 = 31332
3 = 38552
4 = 34052

double 64 bit result:
19375693.015474

Arduino mega result with below function
15.1549

double d_4uint_Double(unsigned int uint1, unsigned int uint2,unsigned int uint3,unsigned int uint4) { // reconstruct the double from 4 unsigned integers

union d_4uint {
double d;
uint16_t i[4];
};
union d_4uint d_number;
d_number.i[0] = uint1;
d_number.i[1] = uint2;
d_number.i[2] = uint3;
d_number.i[3] = uint4;
return d_number.d;
}

The Mega seems to have 32 bits double and long double.

Serial.println(sizeof(double));       // Prints "4".
Serial.println(sizeof(long double));  // Prints "4".

There is a 64bit float library you may have luck with: fp64lib - Arduino Reference

Btw., are you sure that "19375693.015474" is the correct double value derived from those integers?

uint16_t ints[] = { 34052, 38552, 31332, 16754 }; //Reverse order: Endianness
double d = *((double*)ints);
printf("%f\n", d);

Yields: "19375689.412236" on my system..

it is not exactly the same because it is a energy meter counter and i cannot catch the same value in modbus poll .

nevertheless in arduino mega 2560 this code doesn't work because double is 4 bytes instead of 8 bytes

i am working some time on this . thanks

solution:

float Wh,VARh;
float64_t Whf64,VARhf64 ;

float64_t d_4uint_Double(unsigned int uint1, unsigned int uint2,unsigned int uint3,unsigned int uint4) { // reconstruct the float from 2 unsigned integers

union d_4uint {
float64_t d;
uint16_t i[4];
};
union d_4uint d_number;
d_number.i[0] = uint1;
d_number.i[1] = uint2;
d_number.i[2] = uint3;
d_number.i[3] = uint4;
return d_number.d;
}

and the call:
Whf64 = d_4uint_Double(Buffer1[15],Buffer1[14],Buffer1[13],Buffer1[12]);
Wh = fp64_ds(fp64_div(Whf64,fp64_sd(1000.0)));

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.