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
2
3
4
5
6
7
8
9
10
11
12
13
14
// welcome to esptutorial.com

void setup() {
Serial.begin(115200);
char check_sum = 0;
// For example, the data to be verified is 0x11 0x22 0x33 0x44 0x55 0x66
// Add the data, and since it is 8-bit data, we only need the lower 8 bits
check_sum = (0x11 + 0x22 + 0x33 + 0x44 + 0x55 + 0x66) & 0x00ff;

Serial.println(check_sum, HEX); // // Display in hexadecimal
}

void loop() {
}

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// welcome to lingshunlab.com
// 详细说明请查看:https://lingshunlab.com/book/arduino/arduino-esp32-communication-verify-checksum-and-bcc

void setup() {
Serial.begin(115200);
char check_sum = 0;

// For example, the data to be verified is 0x11 0x22 0x33 0x44 0x55
check_sum = 0x11 ^ 0x22 ^ 0x33 ^ 0x44 ^ 0x55;
Serial.println(check_sum, HEX); // Display in hexadecimal
}

void loop() {
}

Upload the code, and you can see the output result in the serial monitor as 11.