-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathTcp.cs
More file actions
53 lines (46 loc) · 1.35 KB
/
Tcp.cs
File metadata and controls
53 lines (46 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using NModbus;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Threading;
namespace ModBus
{
public class Tcp
{
public static int ReadHoldingRegister()
{
try
{
ModbusTcpMasterReadInputsFromModbusSlave();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return 0;
}
/// <summary>
/// Modbus TCP master and slave example.
/// </summary>
public static void ModbusTcpMasterReadInputsFromModbusSlave()
{
string ipAddress = "192.168.2.135";
ushort port = 502;
using TcpClient client = new TcpClient(ipAddress, port);
var factory = new ModbusFactory();
// create the master
IModbusMaster master = factory.CreateMaster(client);
// read holding values
ushort startAddress = "20";
ushort needBytes = 10;
UInt16[] inputs = new UInt16[needBytes];
inputs = master.ReadHoldingRegisters(1, startAddress, needBytes);
for (int i = 0; i < needBytes; i++)
{
Console.WriteLine(inputs[i]);
}
Thread.Sleep(500);
ReadHoldingRegister();
}
}
}