使用NModbus库创建Modbus从站
Nuget安装NModbus库
using NModbus; using System; using System.Net; using System.Net.Sockets; namespace ModbusSlaveTest { internal class Program { static void Main(string[] args) { //设置从站ID和端口 byte slaveId = 1; int port = 502; //创建并配置监听TCP客户端的TcpListener var listener = new TcpListener(new IPAddress(new byte[] { 127, 0, 0, 1 }), port); listener.Start(); //创建从站并开启监听 var factory = new ModbusFactory(); var modbusTcpSlaveNetwork = factory.CreateSlaveNetwork(listener); var slave = factory.CreateSlave(slaveId); modbusTcpSlaveNetwork.AddSlave(slave); modbusTcpSlaveNetwork.ListenAsync(); //输入寄存器 slave.DataStore.InputRegisters.WritePoints(0, new ushort[] { 1, 2, 3 }); //保持寄存器 slave.DataStore.HoldingRegisters.WritePoints(0, new ushort[] { 3, 2, 1 }); //线圈 slave.DataStore.CoilDiscretes.WritePoints(0, new bool[] { true, false, true }); //离散输入 slave.DataStore.CoilInputs.WritePoints(0, new bool[] { true, true, true }); Console.ReadKey(); } } }标签:slave,using,C#,Modbus,CSharpTips,NModbus,var,new,true From: https://www.cnblogs.com/axiaoshuye/p/18427172