以文本方式查看主题

-  Foxtable(狐表)  (http://www.foxtable.com/bbs/index.asp)
--  专家坐堂  (http://www.foxtable.com/bbs/list.asp?boardid=2)
----  CRC-16/modbus  (http://www.foxtable.com/bbs/dispbbs.asp?boardid=2&id=158873)

--  作者:lshshlxsh
--  发布时间:2020/12/5 10:01:00
--  CRC-16/modbus
请问老师  用CRC-16/modbus  怎么计算出 08 00  检验值  70 06

图片点击可在新窗口打开查看此主题相关图片如下:11.png
图片点击可在新窗口打开查看

--  作者:有点蓝
--  发布时间:2020/12/5 10:50:00
--  
全局代码
Public Function ToModbus(ByVal byteData As Byte()) As Byte()
Dim CRC As Byte() = New Byte(1) {}
Dim wCrc As UInt16 = &HFFFF
For i As Integer = 0 To byteData.Length - 1
    wCrc = wCrc Xor Convert.ToUInt16(byteData(i))
    For j As Integer = 0 To 8 - 1
        If (wCrc And &H0001) = 1 Then
            wCrc = wCrc >> 1
            wCrc = wCrc Xor &HA001
        Else
            wCrc = wCrc >> 1
        End If
    Next
Next
CRC(1) = CByte((wCrc And &HFF00) >> 8)
CRC(0) = CByte((wCrc And &H00FF))
Return CRC
End Function

命令窗口
Dim bt() As Byte = {&H08,&H00}
Dim res() As Byte
res = ToModbus(bt)
Output.Show(res(0))
Output.Show(res(1))
Output.Show(&H70)

--  作者:lshshlxsh
--  发布时间:2020/12/5 11:04:00
--  
谢谢老师  这个是可以的  
但是  输入 02 05 00 1e eb 8c 01   没计算错校验 89 eb 报错了

Dim bt() As Byte = {&H02,&H05,&H00,&H1e,&Heb,&H8c,&H01}
Dim res() As Byte
res = ToModbus(bt)
Output.Show(res(0))
Output.Show(res(1))
Output.Show(res(2))



图片点击可在新窗口打开查看此主题相关图片如下:22.png
图片点击可在新窗口打开查看

[此贴子已经被作者于2020/12/5 11:04:26编辑过]

--  作者:有点蓝
--  发布时间:2020/12/5 11:40:00
--  
结果只有2个,哪来的第三个?

Dim bt() As Byte = {&H02,&H05,&H00,&H1e,&Heb,&H8c,&H01}
Dim res() As Byte
res = ToModbus(bt)
Output.Show(res(0))
Output.Show(res(1))
Output.Show(&H89)
Output.Show(&HEB)

--  作者:lshshlxsh
--  发布时间:2020/12/5 12:04:00
--  
好的  谢谢老师 
如果我要把 crc 计算出来的值  传递 写入串口 怎么写入  ?
比如  &H89 ,&Heb   其中 89 ,  eb  是计算出来的结果
Dim Val2() As Byte  = {&H55,&Haa,&H02,&H05,&H00,&H1e,&Heb,&H8c,&H01,&H89,&Heb}
Ports( Vars("COM")  ).Write(Val2, 0, Val2.Length)
[此贴子已经被作者于2020/12/5 14:51:25编辑过]