Skip to content

Instantly share code, notes, and snippets.

@h4tr3d
Last active January 30, 2022 05:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h4tr3d/f2e5963285a5c2af4aa11357c16aea44 to your computer and use it in GitHub Desktop.
Save h4tr3d/f2e5963285a5c2af4aa11357c16aea44 to your computer and use it in GitHub Desktop.
Marshal V-SG4K UART protocol CRC calculation

Protocol described in the official PDF mention CRC byte that complete each request and replay. But omit algorithm for it calculation.

After some researches, something sounds like true was found:

#include <iostream>
#include <cstdlib>

unsigned char checksum(const unsigned char *pcBlock, unsigned char len)
{
    uint32_t accu = 0;
    uint8_t crc = 0;
    
    while (len--)
        accu += *pcBlock++;
    
    accu ^= 0xFFFFFFFF;
    crc = (accu + 1) & 0xFF;
    
    return crc;
}

int main()
{
    const uint8_t buf0[] = {0xAA, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x61, 0x00, 0x00};
    const uint8_t buf1[] = {0xAB, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x61, 0x00, 0x00};
    std::cout << std::hex << (int)checksum(buf0, std::size(buf0)) << std::endl;
    std::cout << std::hex << (int)checksum(buf1, std::size(buf1)) << std::endl;
}

At least, it works as expected for the samples published in the protocol description.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment