一、右键项目—点击管理NuGet程序包
二、安装NModbus4
三、引用
using Modbus.Device;
using System.IO;
using System.IO.Ports;
四、初始化串口
//初始化串口---方式一
private void CreateCom()
{
SerialPort port = new SerialPort();
port.PortName = "COM3";
port.BaudRate = 9600;
port.Parity = Parity.None;
port.DataBits = 8;
port.StopBits = StopBits.One;
}
private SerialPort serialPort;
private ModbusSerialMaster serialMaster;
private void ModbusRtuClient(string portName,int baudRate,Parity parity=Parity.None,int dataBits=8,StopBits stopBits = StopBits.One)
{
//初始化串口---方式二
serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
//打开串口
if (serialPort.IsOpen)
{
serialPort.Open();
//创建Modbus Rtu主站
serialMaster = ModbusSerialMaster.CreateRtu(serialPort);
serialMaster.Transport.ReadTimeout = 1000;//读取数据超时1000ms
serialMaster.Transport.WriteTimeout = 1000;//写数据超时1000ms
serialMaster.Transport.Retries = 3;//重试次数
serialMaster.Transport.WaitToRetryMilliseconds = 500;//重试间隔500ms
}
else
{
serialPort.Close();
serialPort.Open();
serialMaster = ModbusSerialMaster.CreateRtu(serialPort);
}
}
五、写单个寄存器
private void Button_Click_Forw(object sender, RoutedEventArgs e)
{
ModbusRtuClient("COM3", 9600, Parity.None, 8, StopBits.One);
//设置从设备地址和寄存器地址以及值
ushort slaveAddress = 1;
ushort startAddress = 4;
ushort value = 0x0000;
//将值写入寄存器中
serialMaster.WriteSingleRegister((byte)slaveAddress, startAddress, value);
serialPort.Close();
}