-
使用MODBUS协议读取PLC数据的示例代码:
-
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; namespace PLC_Communication { class Program { static void Main(string[] args) { //创建一个TCP客户端 TcpClient client = new TcpClient(); //连接PLC client.Connect("192.168.0.1", 502); //确认连接状态 if (client.Connected) { Console.WriteLine("PLC连接成功!"); //读取PLC数据 byte[] buffer = new byte[12] { 0x00, 0x01, 0x00, 0x00, 0x00, 0x06, 0x01, 0x03, 0x00, 0x64, 0x00, 0x01 }; NetworkStream stream = client.GetStream(); stream.Write(buffer, 0, buffer.Length); byte[] response = new byte[1024]; int count = stream.Read(response, 0, response.Length); for (int i = 0; i < count; i++) { Console.Write(response[i].ToString("X2") + " "); } } else { Console.WriteLine("PLC连接失败!"); } //关闭连接 client.Close(); } } } ``` 其中,`buffer`数组是MODBUS读取数据的命令,`0x00, 0x01`表示PLC的站号,`0x03`表示读取Holding Register,`0x00, 0x64`表示读取起始地址为100的寄存器,`0x00, 0x01`表示读取一个寄存器的数据。读取到的数据会存储在`response`数组中。 以上是一个简单的C#通讯汇川PLC EASY系列的例子,具体的实现方式需要根据实际情况进行调整和修改。