Supported platforms: CODESYS 3.5, CODESYS 3.5 SAFETY

 

Calculate16bitCRC (FUN)

Description

This function calculates a 16-bit CCITT CRC according to given seed and polynomial.

The non-endianness-aware calculation algorithm is following:

  1. Set seed value to register (16-bit)

  2. XOR BYTE data with register’s MSB

  3. While (bits left in BYTE) do

  4. If BYTEs left, get next and go to line 2

  5. The register now contains the remainder.

 

This function is not typically needed by programmer, but is used by higher level checksum functions.

 

This function is NOT endianness-aware. Input data that consists of variables longer than a BYTE has to be converted to big-endian format before usage.

 

This also means that ARRAY and STRUCT members have to be converted to big-endian, and then calculated one by one.

 

Inputs

Input variable name

Data type

Default value

Range

Description

i_pData

POINTER TO BYTE

-

≠ 0

Pointer to data of which checksum is to be calculated.

i_Length

UDINT

-

> 0

Length of the data.

i_Seed

WORD

0

-

Checksum seed value (i.e. the CRC of previous data if several data has common CRC).

i_Polynomial

WORD

1021h

-

Polynomial value for calculation.

Outputs

Output variable name

Data type

Range

Description

o_OutputValid

BOOL

 

Calculated value is valid.

o_ParameterError

BOOL

 

Error in input parameters.

Return value

Data type

Description

WORD

Calculated checksum.

Diagnostics

Conditions

Return value

o_ValueValid

o_ParameterError

i_pData = 0 OR i_Length = 0

0

FALSE

TRUE

i_pData ok AND i_Length > 0

Calculated checksum

TRUE

FALSE

 

Example code

Definitions:

 

table: ARRAY [0..10] OF DWORD;

crc: WORD;

i: INT;

 

 

Code:

 

crc := WORD#0;

 

FOR i := 0 TO 10 DO

    (* Stop if error *)

    IF NOT parametererror THEN

 

        (* Convert pointed data to big-endian *)

        tempDWORD := BigEndianDWORD(i_Data := table[i]);

 

        crc := Calculate16bitCRC(

            i_pData := ADR(tempDWORD),

            i_Length := LibConstants.G_SIZE_OF_U32,

            i_Seed := crc,

            i_Polynomial := 16#1021,

            o_ParameterError => parametererror,

            o_OutputValid => outputvalid

        );

    END_IF

END_FOR

 

 

See also