C# Modbus 之 EasyModbus
直接上代码
public int EasyModbusReadInputRegisters()
{
ModbusClient modbusClient = new ModbusClient(_spHelper.ConfigSerialPort.PortName);
try
{
modbusClient.UnitIdentifier = _dcuInfo.siteId;
modbusClient.Baudrate = _spHelper.ConfigSerialPort.BaudRate;
modbusClient.Parity = (System.IO.Ports.Parity)_spHelper.ConfigSerialPort.Parity;
modbusClient.StopBits = (System.IO.Ports.StopBits)_spHelper.ConfigSerialPort.StopBits;
modbusClient.ConnectionTimeout = 500;
modbusClient.Connect();
int[] result = modbusClient.ReadInputRegisters(54, 1); //地址号
modbusClient.Disconnect();
return result[0];
}
catch (Exception ex)
{
modbusClient.Disconnect();
return -1;
}
}
public bool EasyWriteMultipleRegisters()
{
ModbusClient modbusClient = new ModbusClient(_spHelper.ConfigSerialPort.PortName);
try
{
modbusClient.UnitIdentifier = _dcuInfo.siteId;
modbusClient.Baudrate = _spHelper.ConfigSerialPort.BaudRate;
modbusClient.Parity = (System.IO.Ports.Parity)_spHelper.ConfigSerialPort.Parity;
modbusClient.StopBits = (System.IO.Ports.StopBits)_spHelper.ConfigSerialPort.StopBits;
modbusClient.ConnectionTimeout = 500;
modbusClient.Connect();
int[] registers = new int[] { 3250, 3110 }; //要写的值
ushort startAddress = 54; //从某个地址开始写
modbusClient.WriteMultipleRegisters(startAddress, registers);
modbusClient.Disconnect();
return true;
}
catch (Exception ex)
{
if (modbusClient.Connected)
{
modbusClient.Disconnect();
}
return false;
}
}