Skip to content

Floats, longs and byte order ​

Need: the device stores a float or a 32-bit integer in two registers, and its word order is not the standard ABCD. The script has to read and write in the device's order.

The example first simulates the raw data the device holds:

AddressRaw registersMeaning
0x0200..0x02010x8000, 0x4366Voltage 230.5, float CDAB (low word first)
0x0202..0x02030xE240, 0x0001Energy 123456, long CDAB
0x02040xFF83Temperature −12.5 °C, stored in 0.1 °C units as signed −125
CaseWhat it does
Device dataWrites the raw registers in the table with FC16
Read in the device orderReads the voltage as float_cdab (tolerance 0.1), the energy as long_cdab, and the temperature as signed, then divides by 10
Find the byte orderReads the same registers as both float_abcd and float_cdab to see which makes sense
Write in the device orderWrites 12.5 as float_cdab, then reads back the raw registers

Float example result

What the Log shows:

CaseLog
Read in the device orderTemperature = -12.5 C
Find the byte orderfloat_abcd = -2.4178e-41, float_cdab = 230.5
Write in the device order12.5 as float_cdab = 0, 16712 (16712 = 0x4148)

How to tell which order the device uses: read a known value (the rated voltage, for example) as float_abcd, float_cdab and the other formats. The one that gives a sensible result is the right order. The wrong order usually gives a tiny number (such as -2.4178e-41) or a huge one.

Notes

  • When comparing floats, add a tolerance so rounding does not cause a FAIL.
  • The format only changes how the registers are interpreted, not the data in the device. Each format is described in Concepts › 8. Value formats and byte order.

Download the sample script ​

Sample script

Before running it, start a Slave window on 127.0.0.1:502 and click Listen, then open the script with Open JSON in Script mode and click Run. See How to use the examples.

Roach Modbus Tool by Mr.Roach