• 上位机串行通讯的通用思路


    先上代码:

    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;
            }
        }

    说明:

  • 相关阅读:
    oracle行转列
    JVM设置空间大小
    Spring AOP 业务权限管理
    清晨漫步
    pull解析xml(android)
    今昔何昔
    Spring: Document root element "beans", must match DOCTYPE root "null
    xfire
    心之所向
    Oracle数据库连接
  • 原文地址:https://www.cnblogs.com/feipeng8848/p/7576333.html
Copyright © 2020-2023  润新知