C# 串口实现空闲接收中断功能

  • 设置接收超时毫秒数ReadTimeout
  • 线程接收,每次读一个字节,添加到列表中
  • 接收超时时,捕获异常,生成一帧数据

啥也不说了,看代码

private void Form1_Load(object sender, EventArgs e)
        {
            var sList = SerialPort.GetPortNames();
            this.serialPort1.PortName = sList.Last();
            this.serialPort1.BaudRate = 9600;
            this.serialPort1.ReadTimeout = 10;
            this.serialPort1.Open();
            thread = new Thread(new ThreadStart(ThreadReceive));
            thread.Start();
            timer1.Start();

        }

        Queuebyte>> queueList = new Queuebyte>>();
        Thread thread = null;
        List<byte> receiveList = new List<byte>();
        void ThreadReceive()
        {

            while (true)
            {
                try
                {
                int data = this.serialPort1.ReadByte();
                if (data >= 0)
                    receiveList.Add((byte)data);
                }
                catch
                {
                    if (receiveList.Count > 0)
                    {
                        queueList.Enqueue(receiveList);
                        receiveList = new List<byte>();
                    }
                }
            }
        }


你可能感兴趣的:(C# 串口实现空闲接收中断功能)