我有一个使用Modbus协议的设备。有必要对此设备进行轮询。我有一个读取数据的功能,但是如何查看设备返回的内容?谢谢。
static void Main(string[] args)
{
SerialPort mySerialPort = new SerialPort("COM6");
mySerialPort.BaudRate = 19200;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.ReadTimeout = 450;
mySerialPort.WriteTimeout = 3000;
mySerialPort.Open();
mySerialPort.Write(ReadHoldingRegister(02, 1508, 1), 0, 8);
mySerialPort.Close();
}
public static byte[] ReadHoldingRegister(int id, int startAddress, int length)
{
byte[] data = new byte[8];
byte High, Low;
data[0] = Convert.ToByte(id);
data[1] = Convert.ToByte(3);
byte[] _adr = BitConverter.GetBytes(startAddress - 1);
data[2] = _adr[1];
data[3] = _adr[0];
byte[] _length = BitConverter.GetBytes(length);
data[4] = _length[1];
data[5] = _length[0];
myCRC(data, 6, out High, out Low);
data[6] = Low;
data[7] = High;
return data;
}}
我尝试使用此功能阅读。
byte[] ReadExact(Stream s, int nbytes) {
var buf = new byte[nbytes];
var readpos = 0;
while (readpos < nbytes)
readpos += s.Read(buf, readpos, nbytes - readpos);
return buf; }
从流中读到:
byte[] response = ReadExact(serial.BaseStream, 9);
然后我尝试使用nmodbus,但我找不到任何地方如何返回数据。这是我的代码:
SerialPort serialPort = new SerialPort();
serialPort.PortName = "COM6";
serialPort.BaudRate = 19200;
serialPort.DataBits = 8;
serialPort.Parity = Parity.None;
serialPort.StopBits = StopBits.One;
serialPort.Open();
ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(serialPort);
byte slaveID = 2;
ushort startAddress = 1508;
ushort numOfPoints = 1;
ushort[] holding_register = master.ReadHoldingRegisters(slaveID, startAddress, numOfPoints);
Console.ReadKey();
serialPort.Close();