日期:2014-05-17  浏览次数:20659 次

[分享]C#串口接收数据,数据接受的处理代码
最近看到很多人在问串口的数据处理,尽管已经有人在BLOG中写的很好,但是还是看到很多人在问,所以我把我自己改的一段串口接收的代码发出来供大家参考。可能有很多不好之处,大家见谅,毕竟不是做c#的。主业是做液晶电视和显示器的开发(C语言)。

        private List<byte> buffer = new List<byte>(256);//默认分配1/16页内存,并始终限制不允许超过   
        private byte[] binary_data_1 = new byte[12];//
        private byte[] sendbuff = new byte[4];
        bool bl = false;
        int timeoutCount=0;
        bool timeoutFlag = false;
 private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)//Getting data from Comm Port
        {
            if (IClosing) return;
            try
            {
                timeoutFlag = false;
                Listening = true;//设置标记,说明我已经开始处理数据,一会儿要使用系统UI的。         
                int n = SerialPort1.BytesToRead;
                byte[] buf = new byte[n];
                SerialPort1.Read(buf, 0, n);//读取缓冲数据     
                bool data_1_catched = false;//缓存记录数据是否捕获到    
                buffer.AddRange(buf);
                while (buffer.Count >= 12)
                {
                    byte CRCH, CRCL;
                    byte[] crcTemp = new byte[10];
                    buffer.CopyTo(0, crcTemp, 0, 10);

                    CRCData.CalculateCrc16(crcTemp, out CRCH, out CRCL);
                    if (buffer[10] != CRCH && buffer[11] != CRCL)
                    {
                        buffer.RemoveAt(0);