首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 與松下 FPΣ PLC 通訊實戰(三):完整程式碼與 MEWTOCOL-COM 協定實作

     編輯:關於C語言

完整 WinForms 通訊程式碼

using System; using System.Text; using System.Drawing; using System.Collections;
using System.ComponentModel; using System.Windows.Forms; using System.Data;
namespace complc {
    public class comForm : Form {
        private AxMSCommLib.AxMSComm axMSComm1;
        private TextBox textBox1, textBox2; // 指令輸入、回應顯示
        private Button button1, button2;    // 發送、退出
        private mycom mycom1 = new mycom(); // 封裝通訊邏輯

        [STAThread] static void Main() { Application.Run(new comForm()); }

        private void button1_Click(object sender, EventArgs e) {
            if (!axMSComm1.PortOpen) axMSComm1.PortOpen = true;
            axMSComm1.InputLen = 0; axMSComm1.DTREnable = true; axMSComm1.RTSEnable = true;
            axMSComm1.InputMode = MSCommLib.InputModeConstants.comInputModeText;
            axMSComm1.RThreshold = 1;

            string cmd = textBox1.Text; // 例:%01#RDD9001590016
            axMSComm1.Output = cmd + CalcFCS(cmd) + (char)13;
            textBox2.Text = axMSComm1.Input; // 讀取回應
        }

        private void comForm_Load(object sender, EventArgs e) {
            axMSComm1.CommPort = 1; axMSComm1.Settings = "9600,n,8,1";
        }

        // 幀檢查序列 FCS (BCC) : 從 '%' 起所有字元 ASCII 碼異或,取低位元組轉兩位十六進位
        public string CalcFCS(string s) {
            int fcs = 0; char[] ch = s.ToCharArray();
            for (int i = 1; i < ch.Length; i++) fcs ^= ch[i];
            return fcs.ToString("X2"); // 兩位十六進位
        }
    }
}

結語

程式在 Windows XP + VS.NET 2003 環境測試通過。通訊方式簡單、穩定可靠,適用工業小型監控系統。讀者可依 MEWTOCOL-COM 協定手冊 擴充指令集 (讀/寫 DM 區、位元操作等),實現上位機對 FPΣ PLC 完整監控。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved