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 完整監控。