14.2.3 Comprobación de errores (cálculo CRC)
Ejemplo de la especificación de referencia:
«MODBUS over serial line specification and implementation guide V1.0», capítulo 6.2.2
Example
An example of a C language function performing CRC generation is shown in the following. All of the
possible CRC values are preloaded into two arrays, which are simply indexed as the function increments
through the message buffer. One array contains all of the 256 possible CRC values for the high byte of the
16-bit CRC field, and the other array contains all of the values for the low byte.
Indexing the CRC in this way provides faster execution than would be achieved by calculating a new CRC
value with each new character from the message buffer.
This function performs the swapping of the high/low CRC bytes internally. The bytes are already
swapped in the CRC value that is returned from the function.
Therefore the CRC value returned from the function can be directly placed into the message for
transmission.
The function takes two arguments:
Argument
unsigned char *puchMsg;
unsigned short usDataLen;
CRC Generation Function:
unsigned short CRC16 (puchMsg, usDataLen);
unsigned char *puchMsg;
unsigned short usDataLen;
{
unsigned char uchCRCHi = 0xFF;
unsigned char uchCRCLo = 0xFF;
unsigned uIndex;
while (usDataLen--)
{
}
return (uchCRCHi << 8 | uchCRCLo) ;
}
High-Order Byte Table:
/* Table of CRC values for high-order byte */
static unsigned char auchCRCHi[] = {
0x00,
0xC1,
0x81,
0x40,
0x01,
0xC0,
0x80,
0x41,
0x01,
Leuze electronic
Description
A pointer to the message buffer containing binary data to be used for generating the CRC
The quantity of bytes in the message buffer.
uIndex = uchCRCLo ^ *puchMsgg++ ;
uchCRCLo = uchCRCHi ^ auchCRCHi[uIndex} ;
uchCRCHi = auchCRCLo[uIndex] ;
0x40,
0x01,
0xC0,
0x80,
0x80,
0x41,
0x00,
0xC1,
0xC0,
0x80,
0x41,
0x00,
Puesta en marcha - interfaz RS 485 Modbus
/* The function returns the CRC as a unsigned short type */
/* message to calculate CRC upon */
/* quantity of bytes in message */
/* high byte of CRC initialized */
/* low byte of CRC initialized */
/* will index into CRC lookup table */
/* pass through message buffer */
/* calculate the CRC */
0x41,
0x01,
0xC0,
0x81,
0x40,
0x00,
0xC1,
0x81,
0x40,
CML 720i
0x80,
0x41,
0x00,
0xC1,
0xC1,
0x81,
0x40,
0x01,
0x00,
0xC1,
0x81,
0x40,
0x81,
0xC0,
0x01,
145