码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-09-22 19:11:55      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:this   throw   blog   name   top   receives   com   串行   exce   

先上代码:

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

说明:

 

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

标签:this   throw   blog   name   top   receives   com   串行   exce   

原文地址:http://www.cnblogs.com/feipeng8848/p/7576333.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!