日期:2014-05-18 浏览次数:20905 次
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); continue;//继续下一次循环 } buffer.CopyTo(0, binary_data_1, 0, 12);//复制一条完整数据到具体的数据缓存 data_1_catched = true; buffer.RemoveRange(0, 12);//正确分析一条数据,从缓存中移除数据。 } if (data_1_catched) { foreach (byte data in binary_data_1) RecText = RecText + data.ToString(); bl = true; byte[] dataTemp = new byte[2];// for Hex to singal. int xx=0; int rowNo=binary_data_1[1]; this.Invoke((EventHandler)(delegate { for (int i = 0; i < 4; i++) { dataTemp[0]=binary_data_1[i*2+3]; dataTemp[1]=binary_data_1[i*2+2]; xx=dataTemp[0]*256+dataTemp[1]; this.dataViewMain[i+1, rowNo].Value = xx.ToString(); } })); } } finally { Listening = false; timeoutFlag = true; timeoutCount = 0; } }
class CRC16 { public CRC16() { } private readonly byte[] _auchCRCHi = new byte[]//crc高位表 { 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40, 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41, 0x01, 0xC0, 0x80, 0x41, 0x00, 0x