easymodbus串口模式调试测试
easymodbus串口模式调试测试
public int EasyModbusReadInputRegisters() { ModbusClient modbusClient = new ModbusClient(_spHelper.ConfigSerialPort.PortName); try { modbusClient.UnitIdentifier = _dcuInfo.siteId; modbusClient.Baudrate = _spHelper.ConfigSerialPort.BaudRate; modbusClient.Parity = (System.IO.Ports.Parity)_spHelper.ConfigSerialPort.Parity; modbusClient.StopBits = (System.IO.Ports.StopBits)_spHelper.ConfigSerialPort.StopBits; modbusClient.ConnectionTimeout = 500; modbusClient.Connect(); int[] result = modbusClient.ReadInputRegisters(54, 1); //PLC地址号 modbusClient.Disconnect(); return result[0]; } catch (Exception ex) { modbusClient.Disconnect(); return -1; } } public bool EasyWriteMultipleRegisters() { ModbusClient modbusClient = new ModbusClient(_spHelper.ConfigSerialPort.PortName); try { modbusClient.UnitIdentifier = _dcuInfo.siteId; //从机地址,0x01,0x02 modbusClient.Baudrate = _spHelper.ConfigSerialPort.BaudRate;//波特率 modbusClient.Parity = (System.IO.Ports.Parity)_spHelper.ConfigSerialPort.Parity; modbusClient.StopBits = (System.IO.Ports.StopBits)_spHelper.ConfigSerialPort.StopBits; modbusClient.ConnectionTimeout = 500; modbusClient.Connect(); int[] registers = new int[] { 3250, 3110 }; //要写的值 ushort startAddress = 54; //PLC从某个地址开始写 modbusClient.WriteMultipleRegisters(startAddress, registers); modbusClient.Disconnect(); return true; } catch (Exception ex) { if (modbusClient.Connected) { modbusClient.Disconnect(); } return false; } }
欢迎讨论,相互学习。
cdtxw@foxmail.com