TwinCAT 3 CRC16程序

ST

TYPE ST_CRC_16 :
STRUCT
	nCRCHighLow:WORD;
	nCRCLowHigh:WORD;
	nCRCHigh:BYTE;
	nCRCLow:BYTE;
END_STRUCT
END_TYPE

FUN_CRC_16

FUNCTION FUN_CRC_16 : ST_CRC_16
VAR_INPUT
	pData:POINTER TO BYTE;
	nLength:UINT;
END_VAR
VAR
	nCRCInitial:WORD;
	i:UINT;
	j:UINT;
END_VAR
nCRCInitial:=16#FFFF;
FOR i:=0 TO nLength-1 BY 1 DO
	nCRCInitial:=pData[i] XOR nCRCInitial;
	FOR j:=0 TO 7 BY 1 DO
		IF (nCRCInitial AND 16#01)>0 THEN
			nCRCInitial:=SHR(nCRCInitial,1);
			nCRCInitial:=nCRCInitial XOR 16#A001;//0xa001是由0x8005高低位转换所得
		ELSE
			nCRCInitial:=SHR(nCRCInitial,1);
		END_IF
	END_FOR
END_FOR
FUN_CRC_16.nCRCHigh:=WORD_TO_BYTE(SHR(nCRCInitial,8));
FUN_CRC_16.nCRCLow:=WORD_TO_BYTE(nCRCInitial);
FUN_CRC_16.nCRCHighLow:=nCRCInitial;
FUN_CRC_16.nCRCLowHigh:=SHR(nCRCInitial,8) OR SHL(nCRCInitial,8);

P_CRC_16

PROGRAM P_CRC_16
VAR
	TestDATA:ARRAY[0..7] OF BYTE:=[16#B5,16#FF,16#F0,16#03,16#01,16#01,16#55,16#23];

	TestCRCHigh:BYTE;
	TestCRCLow:BYTE;

	TestCRCFun:ST_CRC_16;
END_VAR
//倍福自带CRC16
TestCRCHigh:=MEM.HighByte(MEM.CRC16_Modbus(pMemoryBlock:=ADR(TestDATA) ,uiLength:=SIZEOF(TestDATA)));
TestCRCLow:=MEM.LowByte(MEM.CRC16_Modbus(pMemoryBlock:=ADR(TestDATA) ,uiLength:=SIZEOF(TestDATA)));

//FUN
TestCRCFun:=FUN_CRC_16(pData:=ADR(TestDATA),nLength:=SIZEOF(TestDATA));

你可能感兴趣的:(TwinCAT,3,TwinCAT,3)