I am getting data in my console program on C# with library Nmodbus4
from a device via modbus rtu
. Format: 32 bit with floating point. My answer is 17445. But the expected value is 660.
How to convert the data and get 660 from 17445?
A little explanation would be nice!
using Modbus.Device;
using Modbus.Utility;
using System;
using System.Collections;
using System.Globalization;
using System.IO.Ports;
namespace Elemer19
{
class Program
{
static void Main(string[] args)
{
string[] pathFolder = ReadDirectory.readDir();
Console.WriteLine("OPENING COM PORT - {0}", pathFolder[0]);
byte slaveID = 4;
ushort startAddress = 0x20c;
ushort numOfPoints = 1;
SerialPort _serialPort = new SerialPort(pathFolder[0],
9600,
Parity.None,
8,
StopBits.One);
try
{
_serialPort.Open();
ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(
_serialPort);
master.Transport.ReadTimeout = 300;
ushort[] data = master.ReadHoldingRegisters(slaveID, startAddress, numOfPoints);
foreach (int item in data)
{
Console.Write("\r\n{0}", item); // 17445
}
}
catch (Exception ex)
{
Console.WriteLine(DateTime.Now.ToString() + ":Connect process " + ex.StackTrace +
"==>" + ex.Message);
}
Console.ReadLine();
}
}}
I found what I was looking for.
ushort[] received = new ushort[] { data[1], data[0] };
byte[] asByte = new byte[4];
Buffer.BlockCopy(received, 0, asByte, 0, 4);
float result = BitConverter.ToSingle(asByte, 0);
Console.Write("Result-{0}", result); // 660