Click here to Skip to main content
15,905,238 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
Hai All,
While i am writing code to calculate CRC16 Modbus. But gives some wrong values. Can any one correct me .......
Here is my code.... my input is ASCII value
VB
Public Function getCRC16(ByVal strInput As String)
        Dim lngCheck As Long
        Dim Power(7) As Integer
        Dim I As Integer
        Dim J As Integer
        Dim Poly As Long
        Dim CRC As Long
        Dim TestBit As Boolean
        Dim TestBit1 As Boolean
        Dim TestBit2 As Boolean

        Poly = &H1021
        CRC = &HFFFF

        For J = 0 To 7
            Power(J) = 2 ^ J
        Next J

        For I = 1 To Len(strInput) Step 2
            lngCheck = Val("&H" & Mid$(strInput, I, 2))
            For J = 7 To 0 Step -1
                If (CRC And 32768) = 32768 Then
                    TestBit1 = True
                Else
                    TestBit1 = False
                End If

                If (lngCheck And Power(J)) = Power(J) Then
                    TestBit2 = True
                Else
                    TestBit2 = False
                End If

                TestBit = TestBit1 Xor TestBit2
                CRC = (CRC And 32767) * 2
                If TestBit = True Then
                    CRC = CRC Xor Poly
                End If

            Next J
        Next I

        Dim tmp As String
        tmp = Hex(CRC)
        getCRC16 = tmp
        MsgBox(tmp)
    End Function
Posted
Updated 11-May-17 18:51pm
v2
Comments
Sandeep Mewara 30-Jul-12 10:42am    
What wrong values? Not clear.
Himachandra 31-Jul-12 1:36am    
For 1234 CRC16 is 30BA
But in this it was giving EC9

1 solution

Usually the CRC16 calculation is table-based (to achieve better performance). You may find it, for example here: "Modbus CRC16 Algorithm in C# and VB.Net"[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 30-Jul-12 19:36pm    
Good reply, my 5.
--SA
Himachandra 31-Jul-12 1:33am    
How can i execute this code in VB.NET
When i click on button i need CRC16 Modbus for Textbox data.......
CPallini 31-Jul-12 3:26am    
Using the (VB) code at the link I provided should be straightforward.
Himachandra 31-Jul-12 3:35am    
How to execute it plzzzzz.......

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900