ModBus-CRC-Local-Version-routine-2
Jump to navigation
Jump to search
//************************************** // Name: Modbus CRC calc // Description:This routine will calculate a 16 bit or two byte, Modbus CRC value. After searching for a long time for a VB.net example , I was unable to find one. I end up reading the Modbus standards(very poor explanation of how to calculate the CRC value) and came up with this. I have read that using a lookup table is a faster way of calculating a CRC value, I have tried using the table and this way, both seem to be just as efficient except this way requires less code. // By: Matthew Lewis // // // Inputs:Just enter the byte array and number of bytes to use from this array and the return value will be the crc calculated. // // Returns:The return value will be the crc calculated. If you pass only the modbus message bytes to the function it will return the crc value. If you pass the modbus message bytes including the crc bytes to the function it will return zero if the modbus message is correct. ( This can be used to check incoming messages from the network) // //Assumes:None // //Side Effects:None //This code is copyrighted and has limited warranties. //Please see http://www.Planet-Source-Code.com/xq/ASP/txtCodeId.6329/lngWId.10/qx/vb/scripts/ShowCode.htm //for details. //************************************** Function CRC16(ByVal MB_aray() As Byte, ByVal mNum As Integer) As Long Dim i As Long = 0 Dim Temp As UInteger = 0 Dim CRC As UInteger = 65535 Dim j As Integer = 0 For i = 0 To mNum - 1 Temp = (CRC) CRC = Temp Xor (MB_aray(i)) For j = 0 To 7 If (CRC And 1) Then CRC = ((CRC >> 1) Xor 40961) '&H1021&) Else CRC = (CRC >> 1) 'And 65535 End If Next j Next i CRC16 = CRC And 65535 End Function