先上代码:

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

说明:

 

相关文章:

  • 2021-05-07
  • 2021-12-01
  • 2021-11-18
  • 2021-06-25
  • 2022-12-23
  • 2022-12-23
  • 2021-07-16
  • 2021-11-29
猜你喜欢
  • 2022-12-23
  • 2021-12-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-01-06
  • 2021-09-20
相关资源
相似解决方案