Search code examples
c++arduinochecksumesp32

How to Calculate Checksum in Arduino/C++?


I'm developing an ESP32(Arduino) interface to communicate to a Fingerprint Device. But I have no idea about the checksum. I found documentation for the Fingerprint device as below.

enter image description here

For example, some of the data packets are followed:

enter image description here

Here, the checksum of the corresponding command packets are. 06 01, F7 02, FA 02, F8 03, FA 02, F9 03

My question is How can I calculate the checksum for a new data packet in Arduino/ C++, for example:

the data packet is:

AA 55 04 01 04 00 00 00 F4 FF 00 00 00 00 00 00 00 00 00 00 00 00 00 ?? ??

What will be the Process?

Thank you!


Solution

  • The specification is very poorly written and vague but just adding up all the bytes in the message and taking the lower 2 bytes of the result seems to produce the right checksum:

    #include <vector>
    #include <cstdint>
    #include <iostream>
    #include <iomanip>
    
    int main()
    {
        std::vector<uint8_t> data{ 0x55, 0xaa, 0x03, 0x01, 0x02, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
        int sum = 0;
        for (auto x : data)
        {
            sum += x;
        }
        uint8_t sum1 = static_cast<uint8_t>(sum & 0xFF);
        uint8_t sum2 = static_cast<uint8_t>((sum >> 8) & 0xFF);
        std::cout << std::setfill('0') << std::hex <<
            std::setw(2) << static_cast<int>(sum1) << " " <<
            std::setw(2) << static_cast<int>(sum2) << "\n";
    }