NModbus4的使用
目录
回到顶部
步骤1:打开串口
SerialPort port = new SerialPort("COM7") port.BaudRate = 9600; port.BaudRate = 9600; port.DataBits = 8; port.Parity = Parity.Odd; port.StopBits = StopBits.One; port.Open();回到顶部
步骤二:创建ModbusSerialMaster,设置超时参数
var master = ModbusSerialMaster.CreateRtu(port); master.Transport.ReadTimeout = 2000; //其中transport还有重试次数和重试间隔时间,默认是3和250 //master.Transport.Retries + " " + master.Transport.WaitToRetryMilliseconds;回到顶部
步骤三:设置协议参数,开始读写
byte slaveID = 3; ushort address = 1; bool[] coils = new bool[8]; coils = master.ReadCoils(slaveID, address, 1);
以上面方式读线圈,超时就会抛出异常。
回到顶部可选步骤四:以async await方式读写
比如点击按钮之后,调用AcquireStatus 方法
private async void AcquireStatus(ModbusSerialMaster master) { byte slaveID = 3; ushort address = 1; bool[] coils=null; master.Transport.ReadTimeout = 2000; try {coils=await master.ReadCoilsAsync(slaveID, address, 1); } catch (Exception ex) { MessageBox.Show("your value " + "无返回值"); } if (coils != null) { this.checkBox1.Checked = coils[0]; MessageBox.Show("your value " + coils[0]); } }标签:coils,步骤,address,NModbus4,slaveID,master,使用,port From: https://www.cnblogs.com/funiyi816/p/16805934.html