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]);
            }

        }

 

转载于:https://www.cnblogs.com/noigel/p/10671982.html

你可能感兴趣的:(NModbus4的使用)