Example code for implementing Modbus Master using NModBus library

freeFree Technical Resource

This content is free to read, suitable for basic learning and search traffic.

Example code for implementing Modbus Master using NModBus library缩略图
using System;
using System.Net.Sockets;
using Modbus.Data;
using Modbus.Device;

namespace ModbusMasterExample
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpClient client = new TcpClient("localhost", 502); // 连接到Modbus TCP服务器
            ModbusIpMaster master = ModbusIpMaster.CreateIp(client); // 创建Modbus Master

            ushort startAddress = 0;
            ushort numRegisters = 10;

            // 读取线圈状态
            bool[] coils = master.ReadCoils(1, startAddress, numRegisters);
            Console.WriteLine("Coils: " + String.Join(", ", coils));

            // 读取离散输入状态
            bool[] inputs = master.ReadInputs(2, startAddress, numRegisters);
            Console.WriteLine("Inputs: " + String.Join(", ", inputs));

            // 读取保持寄存器
            ushort[] holdingRegisters = master.ReadHoldingRegisters(3, startAddress, numRegisters);
            Console.WriteLine("Holding Registers: " + String.Join(", ", holdingRegisters));

            // 读取输入寄存器
            ushort[] inputRegisters = master.ReadInputRegisters(4, startAddress, numRegisters);
            Console.WriteLine("Input Registers: " + String.Join(", ", inputRegisters));
        }
    }
}

Example 2:

private static void Main(string[] args)
        {
            try
            {
                ModbusSerialRtuMasterWriteRegisters();
                ModbusTcpMasterReadInputs();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
 
            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
 
        /// <summary>
        /// Simple Modbus serial RTU master write holding registers example.
        /// </summary>
        public static void ModbusSerialRtuMasterWriteRegisters()
        {
            using (SerialPort port = new SerialPort("COM3"))
            {
                // configure serial port
                port.BaudRate = 9600;
                port.DataBits = 8;
                port.Parity = Parity.None;
                port.StopBits = StopBits.One;
                port.Open();
 
                var factory = new ModbusFactory();
                IModbusMaster master = factory.CreateRtuMaster(port);
 
                byte slaveId = 1;
                ushort startAddress = 100;
                ushort[] registers = new ushort[] { 1, 2, 3 };
 
                // write three registers
                master.WriteMultipleRegisters(slaveId, startAddress, registers);
            }
        }
 
        /// <summary>
        ///     Simple Modbus TCP master read inputs example.
        /// </summary>
        public static void ModbusTcpMasterReadInputs()
        {
            using (TcpClient client = new TcpClient("127.0.0.1", 502))
            {
                var factory = new ModbusFactory();
                IModbusMaster master = factory.CreateMaster(client);
 
                // read five input values
                ushort startAddress = 100;
                ushort numInputs = 5;
                bool[] inputs = master.ReadInputs(0, startAddress, numInputs);
 
                for (int i = 0; i < numInputs; i++)
                {
                    Console.WriteLine($"Input {(startAddress + i)}={(inputs[i] ? 1 : 0)}");
                }
            }
 
            // output:
            // Input 100=0
            // Input 101=0
            // Input 102=0
            // Input 103=0
            // Input 104=0
        }

The above example code creates a Modbus TCP client, and then uses the Modbus Master object to implement the functions of reading coil status, discrete input status, holding registers, and input registers. Of course, modifications need to be made according to the actual situation during actual use.

Download NModbus library on this page

Put this resource to use in a real project?

Go to the Tool Center for message parsing, CRC verification and device debugging, or submit your requirements for selection and integration advice.

Engineer Membership

Turn this article into actionable debugging resources

After activation, you can use advanced message parsing, resource pack downloads, code examples, engineering cases and priority technical support, suitable for real project delivery.

Unlimited Advanced Tools
Resource & Code Packs
Complete Engineering Case Library
Priority Technical Support

Leave a Reply

Your email address will not be published. Required fields are marked *.