Byte-wise CRC16 Calculations

Newbie looking for assistance.
I am reading and writing commands (10 bytes) and messages (up to 100 bytes) hex bytes to and from a device. The packets are terminated with 2-byte CRC16. Because of the variable length packets the CRC16 is calculated byte-wise - the standard look-up table method doesn't give the correct results. I have tried numerous on-line calculators and none give the correct results.

I am able to extract and process received bytes from the msg.payload using function nodes but the algorithm to calculate the CRC for sending commands has me stumped.

I have the following from the C code:

It is CCITT CRC-16. The code is as follows:
/** @brief Add a single byte to a running calculation of a CCITT CRC-16.

  •  Result is in global uCrcAccum.
    
  • @param ch Byte to add.
    */
    void calc_crc(char ch) {
    unsigned int shifter, flag;
    for (shifter = 0x80; shifter; shifter >>= 1) {
    flag = uCrcAccum & 0x8000;
    uCrcAccum <<= 1;
    uCrcAccum |= ((shifter & ch) ? 1 : 0);
    if (flag)
    uCrcAccum ^= 0x1021;
    }
    }

An example 10 byte message with 2 byte CRC: 0222000000000000000081B3

Any assistance would be appreciated. TNX.

Hi,

Did you search anywhere or try anything?

I ask because a quick search for "JavaScript CRC" turned up this

Thanks. I did see that (and quite a few others) but it just didn't 'look' right to me. I'll look at it more closely.

It might be worth using a handful of known data and known checksums and verify them here before you rely on any one solution.

1 Like