Modbus C# Implementation Tutorial

To use Modbus in C#, you first need to install a Modbus library such as NModbus. Then, you can use Modbus by following these steps:

  1. Import the NModbus library:
using Modbus;
  1. Set up Modbus master:
IModbusMaster master = ModbusSerialMaster.CreateRtu(port); // 使用串行RTU通信
IModbusMaster master = ModbusTcpMaster.CreateTcp(ipAddress); // 使用TCP通信
  1. Connect to Modbus slave:
master.Connect(); // 连接到从机
  1. Read the registers of the Modbus slave:
ushort startAddress = 0; // 起始地址
ushort numRegisters = 10; // 寄存器数量
ushort[] registers = master.ReadHoldingRegisters(startAddress, numRegisters);
  1. Write registers to Modbus slave:
ushort startAddress = 0; // 起始地址
ushort[] registers = new ushort[] { 1, 2, 3, 4, 5 }; // 要写入的寄存器的值
master.WriteMultipleRegisters(startAddress, registers);
  1. Disconnect from the Modbus slave:
master.Disconnect(); // 断开连接

This is just the basic usage of Modbus, specific operations may vary depending on your needs. Other Modbus functions such as reading input registers or writing to single registers can also be used as needed.

bannerAds