1.添加 modbus 程序包
2. 创建 ModbusSerialMaster 实例对象
private static ModbusSerialMaster CreateModbusRtu()
{
SerialPort port = new SerialPort();
port.PortName = "COM11";
port.BaudRate = 9600;
port.Parity = Parity.None;
port.DataBits = 8;
port.StopBits = StopBits.One;
port.Open();
//创建Modbus RTU 客户端实例
ModbusSerialMaster master = ModbusSerialMaster.CreateRtu(port);
return master;
}
3. 常用 8个功能码的使用
读
// 读输出线圈 功能码 0x01
byte slaveAddress = 1;//站点
ushort startAddress = 0;//起始地址
ushort numberOfPoints = 10;// 读多少个
bool[] bools = master.ReadCoils(slaveAddress, startAddress, numberOfPoints);
// 读输入线圈 功能码 0x02
byte slaveAddress = 1;//站点
ushort startAddress = 0;//起始地址
ushort numberOfPoints = 10;// 读多少个
bool[] bools = master.ReadInputs(slaveAddress, startAddress, numberOfPoints);
和 输出线圈一样 只不过 功能码换成了 02
读 输入/输出寄存器 功能码 0x04/0x03
ushort[] ushorts = master.ReadHoldingRegisters(slaveAddress, startAddress, numberOfPoints);
ushort[] ushorts = master.ReadInputRegisters(slaveAddress, startAddress, numberOfPoints);
写
写单个线圈
//写入单个线圈
byte slaveAddress = 1;//从站地址
ushort coilAddress = 0;//起始地址
bool value=true;//写 true=1 或 false=0
master.WriteSingleCoil(slaveAddress, coilAddress, value);
//写多个线圈 功能码 0x0F
byte slaveAddress = 1;//从站地址
ushort startAddress = 0;//起始地址
bool [] values = { true,false,true,false };//写 true=1 或 false=0
master.WriteMultipleCoils(slaveAddress, startAddress,values);
//写单个寄存器 功能码 0x06
byte slaveAddress = 1;//站点
ushort registerAddress = 0;//寄存器地址
ushort value = 1001;//要写入的数据
master.WriteSingleRegister(slaveAddress,registerAddress, value);
//写多个寄存器 功能码 0x10
byte slaveAddress = 1;//站点
ushort registerstartAddress = 0;//寄存器起始地址
ushort [] values = {1,2,3,4,5 };//要写入的数据
master.WriteMultipleRegisters(slaveAddress, registerstartAddress, values);
标签:NModbus,C#,demo,ushort,numberOfPoints,master,slaveAddress,startAddress,port From: https://www.cnblogs.com/tomwulog/p/18133240