private void COMDataHandler(object sender, EventArgs e) { if (port_isopen == false) { return; } try { listening = 1; SerialPort sp = (SerialPort)sender; int counter = 0; counter = sp.BytesToRead; byte[] buf = new byte[counter]; sp.Read(buf, 0, counter); int err = 0; setlabel(this.status, "Communicationing"); foreach (byte n in buf) { buffer.Add(n); } //String strr = System.Text.Encoding.Default.GetString(buf); //charfrm.Set_RXBox_Text(strr); while (buffer.Count >= 4) { //2.1 Find Header if (buffer[0] == 0x58 && buffer[1] == 0x5A) //传输数据有帧头,用于判断 { int len = buffer[2]; if (buffer.Count < len) //数据区尚未接收完整 { break; } else { //Got full data, Copy to ReceiveBytes to verify. buffer.CopyTo(0, ReceiveBytes, 0, len); buffer.RemoveRange(0, len); //if(ReceiveBytes[len -3 ] == this.FCS(ReceiveBytes,len)) //Verify FCS Verify Confirmed. { cm.GetSerialData(ReceiveBytes); } } } else //帧头不正确时,记得清除 { buffer.RemoveAt(0); err = 1; if (buffer[0] == 0x58) { err = 0; } if (buf[0] == 'X') { err = 0; } } } if (err == 1) { String str = System.Text.Encoding.Default.GetString(buf); charfrm.Set_RXBox_Text(str); //charfrm.Set_RXBox_Text(buf, counter); } } finally { listening = 0; } }