首先设置PLC的IP地址,设置为ASSII码通讯。

设置PLCIP地址
打开PLC中TCP MC协议,并设置端口

打开MC协议
然后重新启动PLC,就可以通过IP进行PLC的访问了

IP访问PLC
我们对PLC通过TCP编程进行通讯访问。在VS2010中新建类,建立TcpClient实例,传入IP地址及端口参数,测试其连接状态。
/// /// 连接PLC /// /// IP地址 /// port1接口 /// public string connect_PLC(string IpAddress, int port1Num) { string s = "OK"; TcpClient Client = new TcpClient(); try { Client.Connect(IpAddress, port1Num); Client.GetStream().Close(); Client.Close(); } catch (Exception ex) { s = "连接服务器失败!原因:" + ex.ToString(); } return s; }

测试PLC通讯连接
PLC实现了TCP通讯后,接下来就可以传命令实现读取或修改PLC内数值了。按照说明书的MC协议指令进行拼接指令就可以了。

MC协议说明
实现写入PLC指定区域数据命令
/// /// 写入PLC数据 /// /// IP地址 /// port接口 /// 软件元名称(DXC..) /// 开始位置 /// 写入数量 /// 写入的数值(int数组与数量匹配) /// 延后时间(time*250ms) /// public string write_PLC(string plc_IP1, int port1, string memory, int qishi, int cnt, int[] s, int time) { byte[] buffer; byte[] inbuff = new byte[1532]; string RxResponse; string key = ""; TcpClient Client = new TcpClient(); try { Client.Connect(plc_IP1, port1); } catch (Exception ex) { key = "连接服务器失败!原因:" + ex.ToString(); } if (key == "") { StringBuilder str = new StringBuilder(); str.Append("03FF" + time.ToString("x4")); if (memory.ToUpper() == "C") { str.Append("434E"); } else if (memory.ToUpper() == "D") { str.Append("4420"); } else { } str.Append(qishi.ToString("x8")); str.Append(cnt.ToString("x2") + "00"); for (int i = 0; i < s.Length; i++) str.Append(s[i].ToString("x4")); buffer = System.Text.Encoding.Default.GetBytes(str.ToString()); Client.GetStream().Write(buffer, 0, buffer.Length); System.Threading.Thread.Sleep(1500); if (Client.GetStream().DataAvailable) { Client.GetStream().Read(inbuff, 0, inbuff.Length); RxResponse = System.Text.Encoding.Default.GetString(inbuff); key = RxResponse; } Client.GetStream().Close(); Client.Close(); } return key; }
读取文本处理后,写入数据库功操作,这里设置了Timer定时器,自动读取PLC的数值

自动读取PLC数值