使用EasyModbus,NuGet安装EasyModbusTCP 5.6.0
添加命名空间using EasyModbus;
byte _DeviceId = 8;
ModbusClient modbusClient = null;
object _transferLockObj = new object();
public void OpenSerialPort()
{
try
{
modbusClient = new ModbusClient("COM1");
modbusClient.UnitIdentifier = _DeviceId;
modbusClient.Baudrate = _baudRate;
modbusClient.Parity = Parity.None;
modbusClient.StopBits = StopBits.One;
modbusClient.ConnectionTimeout = 500;
modbusClient.Connect();
}
catch (Exception ex)
{
}
}
/// <summary>
/// 写入单个寄存器并获取响应
/// </summary>
public byte[] WriteSingleRegister(ushort regAddr, ushort value)
{
try
{
lock (_transferLockObj)
{
modbusClient.receiveData = null;
modbusClient.WriteSingleRegister(regAddr, value);
byte[] Rec = modbusClient.receiveData;
return Rec;
}
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// 读取寄存器
/// </summary>
public int[] ReadRegisters(ushort regStartAddr, ushort regEndAddr)
{
try
{
lock (_transferLockObj)
{
ushort Lenth = (ushort)(regEndAddr - regStartAddr + 1);
int[] rec = modbusClient.ReadHoldingRegisters(regStartAddr, Lenth);
return rec;
}
}
catch (Exception ex)
{
return null;
}
}
————————————————
版权声明:本文为CSDN博主「glmushroom」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/glmushroom/article/details/125749515