Modbus Serial CRC Checksum C#

Modbus CRC stands for Cyclic Redundancy check.  It is two bytes added to the end of every modbus message for error detection.  Every byte in the message is used to calculate the CRC. The receiving device also calculates the CRC and compares it to the CRC from the sending device. If even one bit in the message is received incorrectly, the CRCs will be different and an error will result.

Below is an Example of CRC RTU using c# to calculate. The return is unsigned integer and needed to be converted by retrieving its byte.

 

uint calc_crc (byte[] ptbuf, int num)
{
	 uint crc16 = 0xffff;
	 uint temp;
	 uint flag;

	 for (int i = 0; i < num; i++) {
		temp = (uint)ptbuf[i]; // temp has the first byte 
		temp &= 0x00ff; // mask the MSB 
		crc16 = crc16 ^ temp; //crc16 XOR with temp 
		for (uint c=0; c<8; c++) {
			flag = crc16 & 0x01; // LSBit di crc16 is mantained
			crc16 = crc16 >> 1; // Lsbit di crc16 is lost 
			if (flag != 0)
				crc16 = crc16 ^ 0x0a001; // crc16 XOR with 0x0a001 
		}
	 }
	 //crc16 = (crc16 >> 8) | (crc16 << 8); // LSB is exchanged with MSB
	 return (crc16);
 } 

Write a Reply or Comment

Your email address will not be published. Required fields are marked *