using System; using System.Collections.Generic; using System.Text; //step1. reference nmodbuspc.dll, and using the namespaces. using Modbus.Device; //for modbus master using System.IO.Ports; //for controlling serial ports using System.Net.Sockets; namespace coil_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 = "COM1"; //the COM port connected to WISE COM1(RS-232) 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); // rewrite the value of address 20 (WISE DO channel 0) //document->Modbus.Device.Namespace->ModbusMaster Class->WriteSingleCoil Method byte slaveID = 1; ushort rewriteAddress = 20; bool rewriteValue = true; master.WriteSingleCoil(slaveID, rewriteAddress, rewriteValue); // read the coil status 20~29 (00020~00029, DO ch0 ~ ch9) of the WISE module. //document->Modbus.Device.Namespace->ModbusMaster Class->ReadCoils Method ushort startAddress = 20; ushort numOfPoints = 10; master.Transport.ReadTimeout = 300; try { bool[] status = master.ReadCoils(slaveID, startAddress, numOfPoints); for (int index = 0; index < status.Length; index++) Console.WriteLine(string.Format("DO[{0}] = {1}", index, status[index])); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("Press enter to exit...."); Console.ReadLine(); } } }