使用VB.Net进行Modbus CRC计算

问题描述 投票:0回答:3

我尝试使用VB.Net计算CRC,但值不同。

例如,如果我使用

05 03 0B D3 00 01
数据 CRC 代码应该是
76 53
但我得到
B6 45

这是我的 VB.Net 代码。

Private Function CRC(data As Byte()) As Byte()
    Dim crcfull As UShort = &HFFFF
    Dim crchigh As Byte = &HF, crclow As Byte = &HFF
    Dim crclsb As Char
    Dim result As Byte() = New Byte(1) {}
    For i As Integer = 0 To (data.Length) - 3
        crcfull = CUShort(crcfull Xor data(i))
        For j As Integer = 0 To 7
            crclsb = ChrW(crcfull And &H1)
            crcfull = CUShort((crcfull >> 1) And &H7FFF)
            If Convert.ToInt32(crclsb) Then
                crcfull = CUShort(crcfull Xor &HA001)
            End If
        Next
    Next
    crchigh = CByte((crcfull >> 8) And &HFF)
    crclow = CByte(crcfull And &HFF)
    Return New Byte(1) {crclow, crchigh}
End Function

问题是什么?

vb.net modbus
3个回答
0
投票

你应该打开选项严格,你会发现这一行有问题。

If Convert.ToInt32(crclsb) Then

我不确定它应该做什么,但你不能用整数执行 If 语句,它必须是布尔值。


0
投票

我并不是真正的 VB 专家,我主要使用 C、C++ 和 C#,但我认为这是您的转换之一,我认为不需要。这对我有用:

Function CRC16(data As Byte()) As Byte()
    Dim crcfull As UInt16 = &HFFFF
    Dim crchigh As Byte, crclow As Byte
    Dim crclsb As Byte

    For i As Integer = 0 To data.Length - 1
        crcfull = crcfull Xor data(i)

        For j As Integer = 0 To 7
            crclsb = crcfull And &H1
            crcfull = crcfull >> 1

            If (crclsb <> 0) Then
                crcfull = crcfull Xor &HA001
            End If
        Next
    Next

    crchigh = (crcfull >> 8) And &HFF
    crclow = crcfull And &HFF
    Return New Byte(1) {crclow, crchigh}
End Function

0
投票

我知道这是一篇旧文章,但如果有人感兴趣,我相信代码是正确的。挑战在于调用代码的方式。

以下测试演示了为什么返回 B6 45 而不是 76 53。

Private Sub Test_CRC()
    'A test demo to verify vb.net CRC code

    Dim data() As Byte

    'a) Original test data - note 6 bytes only
    '   using 05 03 0B D3 00 01
    data = {&H5, &H3, &HB, &HD3, &H0, &H1}
    CRC_so(data)
    'Returns: B6 45 - decimal 182 69

    'b) Full test data sample - full 8 bytes, last two set to zero
    data = {&H5, &H3, &HB, &HD3, &H0, &H1, &H0, &H0}
    CRC_so(data)
    'Returns: 76 53 - decimal 118 83

End Sub

使用该代码有两种选择。要么:

a) 向函数提交一个 8 字节数据数组,用零填充最后两位或

b) 通过更改行来更改代码以仅考虑 6 个字节

For i As Integer = 0 To (data.Length) – 3   'This line is designed for 8-byte data

For i As Integer = 0 To (data. Length) - 1  'This line is designed for 6-byte data

我希望这对您有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.