In serial programming, you must use the RCR verification code to determine whether the received data is correct. The following is the Baidu RCR verification code, which is tested correctly.
1 private void CalculateCRC(byte[] pByte, int nNumberOfBytes, out byte hi, out byte lo) 2 { 3 ushort sum; 4 CalculateCRC(pByte, nNumberOfBytes, out sum); 5 lo = (byte)(sum & 0xFF); 6 hi = (byte)((sum & 0xFF00) >> 8); 7 } 8 9 private void CalculateCRC(byte[] pByte, int nNumberOfBytes, out ushort pChecksum)10 {11 int nBit;12 ushort nShiftedBit;13 pChecksum = 0xFFFF;14 15 for (int nByte = 0; nByte < nNumberOfBytes; nByte++)16 {17 pChecksum ^= pByte[nByte];18 for (nBit = 0; nBit < 8; nBit++)19 {20 if ((pChecksum & 0x1) == 1)21 {22 nShiftedBit = 1;23 }24 else25 {26 nShiftedBit = 0;27 }28 pChecksum >>= 1;29 if (nShiftedBit != 0)30 {31 pChecksum ^= 0xA001;32 }33 }34 }35 }
RCR Verification Code