I have a Real (0.05) and I want to convert it into a Word so I can send it through Modbus. I can send it to two register locations so 2 Words would work.
I have the OSCAT Basic library installed and I am using REAL_TO_DW. This turns the Real 0.05 to a DWORD of 1028281787.
Then I use WORD_OF_DWORD to get Bytes 0 and 1. However, the two words I get are 15690 and 22000.
Am I going about this the wrong way? Would a Real even closer to 0 (like 0.0000005) be harder to send through Modbus?
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
So the Hex value of 0.05 is 3D4CCCCD. So the first WORD is 3D4C and the second CCCD. In decimal this is 15692 and 52429. This is what you need to send over Modbus.
I have a Real (0.05) and I want to convert it into a Word so I can send it through Modbus. I can send it to two register locations so 2 Words would work.
I have the OSCAT Basic library installed and I am using REAL_TO_DW. This turns the Real 0.05 to a DWORD of 1028281787.
Then I use WORD_OF_DWORD to get Bytes 0 and 1. However, the two words I get are 15690 and 22000.
Am I going about this the wrong way? Would a Real even closer to 0 (like 0.0000005) be harder to send through Modbus?
As Modbus doesn't support REALs (32 bit), you need to send it as 2 WORDs (2x 16 bit).
A REAL is internally represented as IEEE 754 value and this determines which bits are set when the value should be e.g. 0.05. See https://en.wikipedia.org/wiki/IEEE_754 and see https://baseconvert.com/ieee-754-floating-point to check which bits are set for the value 0.05.
So the Hex value of 0.05 is 3D4CCCCD. So the first WORD is 3D4C and the second CCCD. In decimal this is 15692 and 52429. This is what you need to send over Modbus.
Maybe an option is to create a UNION type for this with a REAL and ARRAY of 2 words, then it is pretty easy to convert the REAL into 2 WORDs. (see e.g. https://forge.codesys.com/forge/talk/Engineering/thread/8e6b65222e/ or https://forge.codesys.com/forge/talk/Engineering/thread/814c0aa6b2/)
And yes, the IEEE 754 has a limitation in accuracy, so be aware of this.