Conversion data

Hello everybody.
I have a scenario where I receive a float data from a device via MODBUS and then perform the following conversion:

  uint32_t combinedValues;
  float f;
    
      node.readInputRegisters(500, 2);  //Getting data from device, 2 registers.

      combinedValues = (uint32_t)node.getResponseBuffer(0x00) << 16 | node.getResponseBuffer(0x01);
      f  = *(float*)&combinedValues;  //float value here

Now I need to do it in reverse. Through a given a float value I convert to two records of the same format.

Could someone tell me how to do it?

Thanks

If you use a union with that data structure, you can freely write and read from either data without considering actions such as conversion.

union {
  float f;
  unsigned int data[2];
} combinedValues;


You can also assign each data and retrieve it with a float.

  node.readInputRegisters(500, 2); // read data
  
  combinedValues.data[1] = node.getResponseBuffer(0x00); //
  combinedValues.data[0] = node.getResponseBuffer(0x01); // set with data[] 
  
  Serial.println(combinedValues.f, 5); // use with float


You can also assign with a float and retrieve each data.

  combinedValues.f = 1.2345; // set with float
  
  Serial.println(combinedValues.data[1], HEX); //
  Serial.println(combinedValues.data[0], HEX); // use with data[]


EDIT: Fix endianness.
I wrote Serial.println() because I didn't know how to use the data with your program.

Exactly what I needed.

Thank you very much!

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