如何转换通过 modbus 接收的数据?
How to convert data received via modbus?
我正在 C# 上的控制台程序中使用库 Nmodbus4
从设备通过 modbus rtu
获取数据。 格式:32 位浮点数。我的答案是 17445。但是期望值是660.
How to convert the data and get 660 from 17445?
稍微解释一下就好了!
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();
}
}}
我找到了我要找的东西。
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
我正在 C# 上的控制台程序中使用库 Nmodbus4
从设备通过 modbus rtu
获取数据。 格式:32 位浮点数。我的答案是 17445。但是期望值是660.
How to convert the data and get 660 from 17445?
稍微解释一下就好了!
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();
}
}}
我找到了我要找的东西。
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