Preface
Modbus communication is the most commonly used hardware communication coordination, and I don’t have much contact with PLC. Modbus ensures simple and efficient data transmission.
A brief introduction to Modbus protocol
A brief introduction to Modbus
Modbus Poll and Modbus Slave software download: must be downloaded
NModbus
Generally, those starting with N are ported versions of the .NET platform. Such as NLog, Log4Net.
NModbus Github warehouse address
NModbus use
Generally, this kind of small GitHub project does not have a detailed introduction to the GitHub project, and is given to you in the form of a Demo. It is a bit difficult for students who are not strong in programming and English skills.
The official documentation of NModbus simply lists some functions.
Simple to use
Note: Be sure to understand the Modbus Poll and Modbus Slave software first. Let's debug the C# program again.
Here we take Modbus TCP as an example
static void Main(string[] args)
{
Task.Run(ReadModbusTcp) ;
Console.WriteLine("运行完毕");
Console.ReadKey();
}
//简单的Task任务
public async static Task ReadModbusTcp()
{
using (TcpClient client = new TcpClient("127.0.0.1", 502))
{
Console.WriteLine("启动Tcp连接");
var factory = new ModbusFactory();
IModbusMaster master = factory.CreateMaster(client);
master.Transport.ReadTimeout = 2000;
master.Transport.Retries = 10;
// 从地址0开始,读取10个数据。
ushort startAddress = 0;
ushort numInputs = 10;
while (true)
{
var inputs = master.ReadInputRegisters(1, startAddress, numInputs);
for (int i = 0; i < numInputs; i++)
{
Console.WriteLine($"Input {
( startAddress + i )}={
( inputs[i] )}");
}
await Task.Delay(1000);
}
}
}