串口類操作點滴

來源:互聯網
上載者:User

在每次讀串口資料時,時常讀到的不是一包完整的資料,一包完整的資料中的前半段可能是在上次讀到的,後半段資料可能在這次讀到。因此,需要將每次讀到的資料都儲存,再從中分離出每包完整的資料。

 

namespace test
{
    public partial class Form1 : Form
    {
        //串口通訊資料包格式:起始標識符(Hex) + 資料(ANSIC string) + 校正碼(ANSIC string) + 結束標識符(Hex)

        private readonly byte startFlag = 0x02;//資料包起始標識符
        private readonly byte endFlag = 0x03;//資料包結束標識符
        private List<byte> receivedBytesList = new List<byte>();//接收的資料儲存於此

        public Form1()
        {
            InitializeComponent();
        }

        //通過事件觸發來接收串口資料
        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            if (serialPort1.BytesToRead > 0)
            {
                //全部讀取串口資料儲存之
                byte[] bts = new byte[serialPort1.BytesToRead];
                serialPort1.Read(bts, 0, bts.Length);
                receivedBytesList.AddRange(bts);

                //根據起始標識符和結束標識符,在 receivedBytesList 中分離出資料包,並解析
                while (true)
                {
                    int startIndex = receivedBytesList.FindIndex(delegate(byte t) { return t == startFlag; });
                    if (startIndex > -1)
                    {
                        int endIndex = receivedBytesList.FindIndex(startIndex, delegate(byte t) { return t == endFlag; });
                        if (endIndex > startIndex)
                        {
                            //得到我要的一包完整資料,包括起始標識符和結束標識符
                            byte[] myBytes = receivedBytesList.GetRange(startIndex, endIndex - startIndex + 1).ToArray();
                            
                            //其他動作,如解析資料等
                            //Parse(myBytes);

                            //去除已經被解析的資料區段,
                            receivedBytesList.RemoveRange(0, endIndex + 1);
                        }
                        else
                        {
                            break;
                        }
                    }
                    else
                    {
                        break;
                    }
                }

            }
        }
    }
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.