using System; using System.Collections.Generic; using System.Text; //step1. reference nmodbusce.dll, and using the namespaces. using Modbus.Device; //for modbus master using System.IO.Ports; //for controlling serial ports using System.Net.Sockets; using System.Threading; namespace input_status { class Program { static void Main(string[] args) { // create a new SerialPort object with default settings. SerialPort serialPort = new SerialPort(); // set the appropriate properties. serialPort.PortName = "COM2"; serialPort.BaudRate = 115200; serialPort.Parity = Parity.None; serialPort.StopBits = StopBits.One; serialPort.DataBits = 8; serialPort.Open(); // create Modbus RTU Master by the comport client //document->Modbus.Device.Namespace->ModbusSerialMaster Class->CreateRtu Method ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(serialPort); // read the input status 0~9 (10001~10010) of the device slave ID 1. //document->Modbus.Device.Namespace->ModbusMaster Class->ReadInput Method byte slaveID = 1; ushort startAddress = 0; ushort numOfPoints = 10; master.Transport.ReadTimeout = 300; try { bool[] status = master.ReadInputs(slaveID, startAddress, numOfPoints); for (int index = 0; index < status.Length; index++) Console.WriteLine(string.Format("status[{0}] = {1}", index, status[index])); } catch (Exception ex) { Console.WriteLine(ex.Message); } Thread.Sleep(3000); } } }