C#上位机读写PLC案例,TCP通信,通讯部分封装成类

C#上位机读写PLC案例,TCP通信,通讯部分封装成类,没有加密,都是源码,注释齐全,纯源码,此版本支持汇川全系列PLC的ModebusTCP通讯的读写操作。
C#上位机与汇川全系列PLC走ModbusTCP通信实例源码
C# socket编程 上位机一键修改plc参数
汇川TCP UDP socket通讯示例,亲测可用,适合学习
通讯相关程序写成库,都是源码,可以直接复用
关键代码注释清晰
支持汇川全系列plc的modbusTCP通讯,
可以导入导出变量表
C005
请添加图片描述

YID:179703969584264

请添加图片描述
请添加图片描述
请添加图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
下面是一个 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; } } } ``` 需要注意的是,这只是一个简单的示例程序,实际应用中需要根据具体的设备和通讯方式进行修改和调试。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值