C# 上位机与plc基于modbus tcp通讯程序
时间: 2023-08-30 21:06:41 浏览: 96
下面是一个 C# 上位机与 PLC 基于 Modbus TCP 通讯的程序示例:
```csharp
using System;
using System.Net.Sockets;
using System.Threading;
namespace ModbusTcp
{
class Program
{
static void Main(string[] args)
{
// PLC IP地址和端口号
string ip = "192.168.1.100";
int port = 502;
// 创建TCP连接
TcpClient client = new TcpClient(ip, port);
// 创建Modbus协议对象
ModbusTcpProtocol protocol = new ModbusTcpProtocol(client);
// 连接到PLC
protocol.Connect();
// 读取PLC寄存器值
ushort[] values = protocol.ReadHoldingRegisters(0, 10);
// 输出读取到的值
for (int i = 0; i < values.Length; i++)
{
Console.WriteLine("Register {0}: {1}", i, values[i]);
}
// 关闭连接
protocol.Disconnect();
client.Close();
}
}
// Modbus TCP 协议类
class ModbusTcpProtocol
{
TcpClient client; // TCP客户端对象
NetworkStream stream; // 网络流对象
// 构造函数
public ModbusTcpProtocol(TcpClient client)
{
this.client = client;
this.stream = client.GetStream();
}
// 连接到PLC
public void Connect()
{
// 发送连接请求
byte[] connectRequest = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, 0x00, 0x00, 0x00, 0x0A };
stream.Write(connectRequest, 0, connectRequest.Length);
// 读取响应
byte[] response = new byte[12];
stream.Read(response, 0, response.Length);
// 检查响应是否为连接确认
if (response[7] != 0x03 || response[8] != 0x00 || response[9] != 0x00 || response[10] != 0x00 || response[11] != 0x0A)
{
throw new Exception("Failed to connect to PLC");
}
}
// 关闭连接
public void Disconnect()
{
// 发送断开连接请求
byte[] disconnectRequest = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, 0x00, 0x00, 0x00, 0x0A };
stream.Write(disconnectRequest, 0, disconnectRequest.Length);
}
// 读取保持寄存器
public ushort[] ReadHoldingRegisters(ushort startAddress, ushort numRegisters)
{
// 发送读取请求
byte[] request = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, (byte)(startAddress >> 8), (byte)startAddress, (byte)(numRegisters >> 8), (byte)numRegisters };
stream.Write(request, 0, request.Length);
// 读取响应
byte[] response = new byte[9 + numRegisters * 2];
stream.Read(response, 0, response.Length);
// 解析响应
ushort[] values = new ushort[numRegisters];
for (int i = 0; i < numRegisters; i++)
{
values[i] = (ushort)(response[9 + i * 2] << 8 | response[10 + i * 2]);
}
return values;
}
}
}
```
需要注意的是,这只是一个简单的示例程序,实际应用中需要根据具体的设备和通讯方式进行修改和调试。