Search code examples
c#modbusrs485

MODBUS Word conversion


I am getting data from a Carlo Gavazzi meter. The MODBUS data is 2 words in length, it is a signed 32 bit integer. How do I convert this into a real number in C#. I get an integer back, for example, 16002, I want to be able to convert this into the value that is displayed on the front of the device.

In summary: Convert two-word 32 bit signed integer into its real value.


Solution

  • Converting 2 16-bit unsigned registers into a 32-bit signed value can be done as shown below. This can be done in one statement, but I will do it in steps for clarity. Assuming that you have the upper and lower words (16-bit) in upper16 and lower 16 respectively:

    UInt32 uint32 = upper16;
    uint32 <<= 16;
    uint32 |= lower16;
    Int32 sint32 = (Int32)uint32;
    

    Based on this statement in the documentation:

    For all the formats the byte order (inside the single word) is MSB->LSB. 
    In INT32, UINT32 and UINT64 formats, the word order is LSW-> MSW."
    

    It looks like

    lower16 = address 30053
    upper16 = address 30054
    

    You mentioned in a comment that it has a scale of 10. Usually that is done so that you can give some precision to the value (floating point value). So you would probably do:

    double value = sint32 / 10.0;
    

    OR

    double kW = sint32 / 10.0; // In your case