先上代码:
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; } }
说明: