ESP32 Data Verification Techniques in Serial Communication A Hands-On Guide to Checksum and BCC Methods
esptutorial (esptutorial.com) introduces some data verification methods used in serial communication or communication protocols to ensure that the received data is complete and correct. Common methods include checksum and Block Check Character (BCC).
Checksum
Checksum is used in data processing and data communication to verify the sum of a set of data items. It is usually represented in hexadecimal. If the checksum value exceeds hexadecimal FF, which is 255, its complement is required as the checksum. It is commonly used in communication, especially long-distance communication, to ensure data integrity and accuracy.
The following is a checksum method used by a product encountered by Lingshun Lab. In this case, the sum exceeding 255 does not use the complement, so the specific checksum method needs to refer to the product manual or be defined by you.
The checksum method of a certain product adds up the data to be verified, but the maximum value of 8-bit data can only be 256, so we only need the lower 8 bits of the data, using &0x00ff
to get it.
For example, the hexadecimal data group to be verified: 11 22 33 44 55 66
Calculation: 11 + 22 + 33 + 44 + 55 + 66 = 0x165 = 357 (decimal) = 0000 0001 0110 0101
0000 0001 0110 0101 & 0x00ff = 0110 0101 = 101 (decimal) = 0x65
The checksum is: 65
Test Code
1 | // welcome to esptutorial.com |
Upload the code, and you can see the output result in the serial monitor as 65
.
Block Check Character (BCC)
It is actually a parity check, and it is also the most commonly used and efficient verification method. The so-called BCC verification method is to XOR each byte of data (usually two 16-bit characters) to get the checksum.
For example, the hexadecimal data group to be verified: 11 22 33 44 55
Calculation: 0x11 xor 0x22 xor 0x33 xor 0x44 xor 0x55 = 0x11
The checksum is: 0x11
Test Code
1 | // welcome to lingshunlab.com |
Upload the code, and you can see the output result in the serial monitor as 11
.