上位机串行通讯的通用思路
Posted feipeng8848
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了上位机串行通讯的通用思路相关的知识,希望对你有一定的参考价值。
先上代码:
public class SerialPortServer { //字段 SerialPort SP = new SerialPort(); int DelayTime = 5000;//默认是5s string Info = ""; string SendStringBuffer = ""; string ReceiveStringBuffer = ""; //构造函数 public SerialPortServer(string COM, int BaudRate, int DelayTime) { //init sp SP.PortName = COM; SP.BaudRate = BaudRate; SP.StopBits = StopBits.One; SP.Parity = Parity.None; //init DelayTime this.DelayTime = DelayTime; } //公共方法 public string OpenSP() { try { SP.Open(); } catch (Exception) { return "Open Error"; throw; } return "OK"; } public void CloseSP() { SP.Close(); } //私有方法 private void MainMission() { while (true) { if ("" != SendStringBuffer) { SendString(); } Thread.Sleep(DelayTime); Receive(); Parse(); } } private void Receive() { ReceiveStringBuffer = SP.ReadExisting(); } private void SendString() { SP.Write(SendStringBuffer); SendStringBuffer = ""; } private void Parse() { Info = ReceiveStringBuffer.Substring(0,3); } //get方法 public string GetInfo() { return this.Info; } //set方法 public void SendFrame(string Frame) { this.SendStringBuffer = Frame; } }
说明:
以上是关于上位机串行通讯的通用思路的主要内容,如果未能解决你的问题,请参考以下文章