步骤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);
以上面方式读线圈,超时就会抛出异常。