PLC實現TCP通訊

首先設置PLC的IP地址,設置為ASSII碼通訊。

PLC實現TCP通訊

設置PLCIP地址

打開PLC中TCP MC協議,並設置端口

PLC實現TCP通訊

打開MC協議

然後重新啟動PLC,就可以通過IP進行PLC的訪問了

PLC實現TCP通訊

IP訪問PLC

我們對PLC通過TCP編程進行通訊訪問。在VS2010中新建類,建立TcpClient實例,傳入IP地址及端口參數,測試其連接狀態。

<code>        /// 
        /// 連接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;
        }/<code>
PLC實現TCP通訊

測試PLC通訊連接

PLC實現了TCP通訊後,接下來就可以傳命令實現讀取或修改PLC內數值了。按照說明書的MC協議指令進行拼接指令就可以了。

PLC實現TCP通訊

MC協議說明

實現寫入PLC指定區域數據命令

<code>        /// 
        /// 寫入PLC數據
        /// 
        /// IP地址
        /// port接口
        /// 軟件元名稱(D\X\C..)
        /// 開始位置
        /// 寫入數量
        /// 寫入的數值(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;
        }/<code>

讀取文本處理後,寫入數據庫功操作,這裡設置了Timer定時器,自動讀取PLC的數值

PLC實現TCP通訊

自動讀取PLC數值


分享到:


相關文章: