Question

I am trying to calculate CRC of 2 byte. I have Table of CRC values for high–order byte and low–order byte.

static unsigned char auchCRCHi[] = {0x00, 0xC1, 0x81, 0x40, 0x01............0x40} ;
static char auchCRCLo[] = {0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03....0x40} ;

These are used in below function to calculate CRC.

unsigned short CRC16(unsigned char* puchMsg, unsigned short usDataLen)
{
    unsigned char uchCRCHi = 0xFF ; /* high byte of CRC initialized */
    unsigned char uchCRCLo = 0xFF ; /* low byte of CRC initialized */
    unsigned uIndex ; /* will index into CRC lookup table */

    while (usDataLen--) /* pass through message buffer */
    {
        uIndex = uchCRCHi ^ *puchMsg++ ; /* calculate the CRC */
        uchCRCHi = uchCRCLo ^ auchCRCHi[uIndex] ;
        uchCRCLo = auchCRCLo[uIndex] ;
     }

     return (uchCRCHi << 8 | uchCRCLo) ;
}

In the above function "puchMsg" is A pointer to the message buffer containing binary data to be used for generating the CRC and "usDataLen" is the quantity of bytes in the message buffer.

The function returns the CRC as a type unsigned short.

Now I have to append this CRC byte at the end of my message.

Without CRC when i send my data in the following way it works

char str[6]={0x01,0x01,0x00,0x01,0x00,0x20};// sending hex of $$S??
serialObj.send(str, 6);

Now I have to calculate the CRC and append it at the end of str making it 8 byte.

unsigned char str1[8] ={0x01,0x01,0x00,0x01,0x00, 0x20};
unsigned char* str2 = str1;
unsigned short test;
test= CRC16(str1,8);

here test will contain the returned CRC as unsigned short. How to append it as last 2 byte in str1[8].

Was it helpful?

Solution

It's pretty simple, one example would be:

unsigned char buffer[8] ={0x01, 0x01, 0x00, 0x01, 0x00, 0x20, 0x00, 0x00};
unsigned short crc = CRC16(buffer, 8); // Calculates the CRC16 of all 8 bytes
buffer[6] = ((char*) &crc)[0];
buffer[7] = ((char*) &crc)[1];

It depends on the byte order of the destination system, you may swap 0 with 1 above.

Edit: Alternative:

*((unsigned short*) &buffer[6]) = crc;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top