Example #1
0
        /// <summary>
        ///     Modbus serial ASCII master and slave example.
        /// </summary>
        public static void ModbusSerialAsciiMasterReadRegistersFromModbusSlave()
        {
            using (SerialPort masterPort = new SerialPort("COM1"))
                using (SerialPort slavePort = new SerialPort("COM2"))
                {
                    // configure serial ports
                    masterPort.BaudRate = slavePort.BaudRate = 9600;
                    masterPort.DataBits = slavePort.DataBits = 8;
                    masterPort.Parity   = slavePort.Parity = Parity.None;
                    masterPort.StopBits = slavePort.StopBits = StopBits.One;
                    masterPort.Open();
                    slavePort.Open();

                    var slaveAdapter = new SerialPortAdapter(slavePort);
                    // create modbus slave on seperate thread
                    byte slaveId = 1;

                    var factory = new ModbusFactory();

                    var transport = factory.CreateAsciiTransport(slaveAdapter);

                    var network = factory.CreateSlaveNetwork(transport);

                    var slave = factory.CreateSlave(slaveId);

                    network.AddSlave(slave);

                    var listenTask = network.ListenAsync();

                    var masterAdapter = new SerialPortAdapter(masterPort);

                    var masterTransport = factory.CreateAsciiTransport(masterAdapter);

                    // create modbus master
                    IModbusSerialMaster master = factory.CreateMaster(masterTransport);

                    master.Transport.Retries = 5;
                    ushort startAddress = 100;
                    ushort numRegisters = 5;

                    // read five register values
                    ushort[] registers = master.ReadHoldingRegisters(slaveId, startAddress, numRegisters);

                    for (int i = 0; i < numRegisters; i++)
                    {
                        Console.WriteLine($"Register {(startAddress + i)}={registers[i]}");
                    }
                }

            // output
            // Register 100=0
            // Register 101=0
            // Register 102=0
            // Register 103=0
            // Register 104=0
        }