using Modbus.Device; using Modbus.Extensions.Enron; using System; using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp21 { internal class Program { static void Main(string[] args)//添加NModbus4库后设置相关参数 { //确定通讯方式 SerialPort serialPort = new SerialPort("COM1");// 实例化并选择COM1端口 serialPort.BaudRate = 9600;//设置波特率 serialPort.DataBits = 8;//数据位 serialPort.Parity = Parity.None;//偶校验 serialPort.StopBits = StopBits.One;//停止位 serialPort.Open();//打开端口 //发送通讯结果 var master = ModbusSerialMaster.CreateRtu(serialPort); ushort[] values = master.ReadHoldingRegisters(1, 10, 4);//从站1,地址10,数量4 //将接收到的结果输出屏幕 Console.WriteLine(values[0] + " " + values[1] + " " + values[2] + " " + values[3]); //写入传递数据 Console.WriteLine( "正在写入 数值到10寄存器" ); master.WriteSingleRegister(1, 20, 12345);//将从站地址1 末位的数值666写入(中间)第20-29个寄存器 master.WriteSingleRegister(1, 21, 12345); master.WriteSingleRegister(1, 22, 12456); master.WriteSingleRegister(1, 23, 12345); master.WriteSingleRegister(1, 24, 12456); master.WriteSingleRegister(1, 25, 12345); master.WriteSingleRegister(1, 26, 12456); master.WriteSingleRegister(1, 27, 12456); master.WriteSingleRegister(1, 28, 12345); master.WriteSingleRegister(1, 29, 12456); Console.WriteLine( "写入完成"); Console.WriteLine("读取线圈状态"); bool[] coilValues = master.ReadCoils(1,0,2);//设置从站地址1,起止地址0,读取数2 Console.WriteLine(coilValues[0] + " " + coilValues[1]); Console.WriteLine("写入一个线圈状态true到寄存器3"); master.WriteSingleCoil(1, 3, true);//写入从站地址1,地址3,状态true Console.ReadKey(); } } }
标签:练手,Console,NModbus4,System,serialPort,master,using,WriteSingleRegister From: https://www.cnblogs.com/pdaxing/p/17636192.html