Float32(big endian)

Hi
Got stuck trying to get voltage data from this power meter :https://dariancabot.com/wp-content/uploads/2024/08/Eastron-SDM120-Modbus-protocol-V2.1.pdf.
As you can see it uses 2x16 bit registers to store the data.
Using Terminal I can see query and response no problem.
The issue is the 32 bit float(big endian).Tried a few examples from the Forum but so far no luck.Just keeps returning 00.0.
Here's the code so far.

#include <ModbusMaster.h>
#include <SoftwareSerial.h>
 
// Create a SoftwareSerial object to communicate with the MAX485 module
SoftwareSerial mySerial(9, 10); // RX, TX
 
// Create a ModbusMaster object
ModbusMaster node;
 
void setup() {
  // Initialize serial communication for debugging
  Serial.begin(9600);
  // Initialize SoftwareSerial for Modbus communication
  mySerial.begin(9600);
 
  // Initialize Modbus communication with the Modbus slave ID 1
  node.begin(1, mySerial); }



 

 
void loop() {
  uint8_t result;   // Variable to store the result of Modbus operations
  uint16_t regs [2]; // Array to store the data read from the Modbus slave
 
  // Read 2 holding registers starting at address 0x0000
  // This function sends a Modbus request to the slave to read the registers
  result = node.readInputRegisters(0x0000, 2);
 
  // If the read is successful, process the data
  if (result == node.ku8MBSuccess) {
    // Get the response data from the response buffer
  uint16_t regs[2]={0x0000,0x0001}; 
  long int num = (((unsigned long)regs[0] & 0x0000) << 16) | (regs[1] & 0x0001);
  float numf;
  memcpy(&numf,&num,8);
  Serial.println(numf);
}
delay(2000); 
}

That doesn't even use the register values you requested.
Try this:

result = node.readInputRegisters(0x0000, 2);

if (result == node.ku8MBSuccess) {
    uint16_t hi = node.getResponseBuffer(0);
    uint16_t lo = node.getResponseBuffer(1);

    uint32_t raw = ((uint32_t)hi << 16) | lo;

    float numf;
    memcpy(&numf, &raw, sizeof(numf));

    Serial.println(numf);
}

If output is weird, swap hi and lo.

Thanks.It works.

It may not be causing a problem, but I note that you have two different arrays named regs, each with their own scope.

At best, this is confusing and at worst could cause problems

It's a heck of a lot more directly simple than interpreting 32 bits to get a float. But here's what that takes. Don't say pun!

Decades ago I was easily able to imagine intel 386 doing those steps while I despertly tried to run Autocad on it without FPU. :sweat_smile:

You can't simply construct a float from two 16-bit integers. A standard IEEE-754 single-precision floating-point value consists of a 1-bit sign, an 8-bit exponent, and a 23-bit fraction (mantissa). Since normalized numbers have an implicit leading 1, the effective mantissa precision is 24 bits. Therefore, combining two 16-bit integers does not automatically produce a valid floating-point representation unless you explicitly reconstruct the IEEE-754 bit layout.

Hi Guys
Been tidying the code and I think now I've got it right.My apologies.I'll post it for everyone to see.You won't believe how frustrated i was.Tried for a week,searched everywhere but sadly most people once they problem was answered,won't publish the final code or just walked away.Or only snippets of the code were exchanged and got even more confused.Or they weren't tested and simply won't work.
Couldn't believe,something so important as a float32,wasn't all over and explained properly so everyone could understand.Being a lifetime PLC ladder logic bloke it will take sometime to get used to C++.Only used it at some logistics place where they're using this Steeplechase software.Anyway enough of ranting.
Again thanks for helping.Also later I'll be posting this sketch with the added ability to drive an LCD display.Tested and guaranteed to work.

  #include <ModbusMaster.h>
  #include <SoftwareSerial.h>
 
  // Create a SoftwareSerial object to communicate with the MAX485 module
  SoftwareSerial mySerial(9, 10); // RX, TX
 
  // Create a ModbusMaster object
  ModbusMaster node;
 
void setup() {
  // Initialize serial communication for debugging
  Serial.begin(9600);
  // Initialize SoftwareSerial for Modbus communication
  mySerial.begin(9600);
 
  // Initialize Modbus communication with the Modbus slave ID 1
  node.begin(1, mySerial); }
 
void loop() {
  uint8_t result;   // Variable to store the result of Modbus operations
  uint16_t data [2]; // Array to store the data read from the Modbus slave
 
  // Read 2 holding registers starting at address 0x0000
  // This function sends a Modbus request to the slave to read the registers
  result = node.readInputRegisters(0x0000, 2);
 
  // If the read is successful, process the data
  if (result == node.ku8MBSuccess) {

  // Get the response data from the response buffer
  data[0] = node.getResponseBuffer(0);
  data[1] = node.getResponseBuffer(1);

  // Process the response data
  uint32_t raw = ((uint32_t)data[0] << 16) | data[1];
  float numf;
  memcpy(&numf, &raw, sizeof(numf));

  // Send to Serial Monitor
  Serial.print("Voltage: ");
  Serial.print(numf);
  Serial.println(" Vac");
  } 

  // For stability,pause before next data request
  delay(1000); 
  }


I prefer to get some feedback if read is not successful.
Library offers basic error handling:

else 
  {
    Serial.print("Modbus exception: ");
    Serial.println(result, HEX);
  }

Interesting!

An Example;
LM35 analog temperature sensor produces a DC signal, which I convert to a floating-point number using the following formula:

float myTemp = 5.0/1023,0)*100*analogRead(A0));

In the above, myTemp is a 4-byte-wide memory space which contains IEEE-754 formatted 32-bit float data.

Using the memcpy() function, I can transfer the above-mentioned 32-bit number into a 16-bit, two-element-wide array like:

unsigned int myData[2];
flat myTemp;
memcpy(&myData, &myTemp, 4);     //lilltle endian.

Will the RH expression in the following statement not be evaluated as a 32-bit IEEE-754-formatted float?
unsigned long int data = myData[1] << 16 | myData[0];

I think you're missing what's going on.
The device provides a 32bit float number, but the modbus protocol/library only supports the read/write of 16bit "registers", so the data arrives as two 16bit binary chunks ("unsigned integers") which the code has to reassembly into a float in the format that the avr code understands.

unless the exponent is 0 in which case the implied bit is 0.

The link in post #5 shows the complete layout.

So we can translate that both ways. Bitwise logic lets us do that.

Oh dear... with no FPU it is faster and more precise to work with integers in small units than to use dirt-in-sand IEEE floats within 9 or 19 places.

Once we had CPU's with FPU's, I found 64-bit doubles acceptable with rounding. A few ops with a 32 bit float and the low-order is garbage, with 64 bits the garbage is farther down.

You can search for 'dirt in sand' to read more.

You don't need raw. The name data compiles to the base address of the data[] array. You don't need the reference &, just the name data.

@jcampsaust

Example:

void setup() {
  Serial.begin(9600);
  byte data[] = {0xCD, 0xCC, 0x8A, 0x41};  //binart32 formatted data for 17.35
  float numFloat;
  memcpy(&numFloat, data, 4);  //type of numFloat dicates data is in IEEE-754 format
  Serial.print(numFloat, 2); //shows: 17.35
}

void loop() {}

K&R "invented" unions for such conversion...

//    FILE: union.ino
//  AUTHOR: Rob Tillaart

union
{
  uint16_t data[2];
  float f;
} convert;


void setup()
{
  Serial.begin(115200);

  convert.data[0] = 0xCCCD;
  convert.data[1] = 0x418A;
  Serial.println(convert.f, 2); // shows: 17.35

  //  and reverse
  convert.f = 3.141592;
  Serial.println(convert.data[0], HEX);
  Serial.println(convert.data[1], HEX);

  Serial.print("SIZE:\t");
  Serial.println(sizeof(convert));
}

void loop() {}

// -- END OF FILE --

Output

17.35
FD8
4049
SIZE:	4

No need for memcpy, no extra RAM

1. I used the union structure for years to convert data from one type to another. However, after learning from experienced developers that union relies on type punning which leads to undefined behaviour in C++, I stopped using it. Should we still encourage others to use it?

2. The union based sketch consumed 3094 bytes of flash and 210 bytes of RAM.
3. memcpy() based consumed 2984 bytes of flash and 210 bytes of RAM.
4. Why have you not used a tag for your union structure? I mean, something like:

union  myData
{
  uint16_t data[2];
  float f;
} convert;

We should encourage others to understand HOW unions work, so they can decide themselves if it fit their project. If you have enough memory and CPU/MCU cycles unions are not needed.
If you need to squeeze every byte possible.....

For your students you can create a nice union from a struct with three bit fields and a float. Easy to split up a float in sign, mantissa and exponent. (left as an exercise).

Union uses 90 bytes more PROGMEM and 4 bytes less RAM.
Which IDE / board?


output IDE 1.8.19 UNO R3 - union

Sketch uses 2964 bytes (9%) of program storage space. Maximum is 32256 bytes.
Global variables use 204 bytes (9%) of dynamic memory, leaving 1844 bytes for local variables. Maximum is 2048 bytes.

output IDE 1.8.19 UNO R3 - memcpy

Sketch uses 2932 bytes (9%) of program storage space. Maximum is 32256 bytes.
Global variables use 200 bytes (9%) of dynamic memory, leaving 1848 bytes for local variables. Maximum is 2048 bytes.

Union uses 32 bytes more PROGMEM and 4 bytes less RAM.

I am lazy

cough