1、modbus rtu协议可以算是一种事实上的工业标准协议,为许多仪表、PLC等所支持。以前有几个用户问如何使用VB编程来与我们的KND-K3系列PLC通讯,于是整了一个demo程序。这次把这个demo共享,希望能给大家一点帮助。1) 模块文件:modCRC,其中包含了CRC校验的函数。'data 待校验的数组名称'no 数组中元素个数'btLoCRC 算出的CRC高字节'btHiCRC 算出的CRC低字节Public Function CalCRC16Fast(data() As Byte, no As
2、Integer, btLoCRC As Byte, btHiCRC As Byte) As String Dim CL As Byte, CH As Byte '多项式码&HA001 Dim SaveHi As Byte, SaveLo As Byte Dim i As Integer Dim Flag As Integer btHiCRC = &HFF btLoCRC = &HFF CL = &H1 CH = &HA0
3、 For i = 0 To (no - 1) btHiCRC = btHiCRC Xor data(i) '每一个数据与CRC寄存器进行异或 For Flag = 0 To 7 SaveHi = btLoCRC SaveLo = btHiCRC btLoCRC = btLoCRC 2 '高位右移一位 btHiCRC = btHiCRC 2 '低位
4、右移一位 If ((SaveHi And &H1) = &H1) Then '如果高位字节最后一位为1 btHiCRC = btHiCRC Or &H80 '则低位字节右移后前面补1 End If '否则自动补0 If ((SaveLo And &H1) = &H1) Then '如果LSB为1,则与多项式码进行异或 btLoCRC = btLoCRC Xo
5、r CH btHiCRC = btHiCRC Xor CL End If Next Flag Next i Dim ReturnData(1) As Byte ReturnData(0) = btHiCRC 'CRC高位 ReturnData(1) = btLoCRC 'CRC低位 CalCRC16Fast = ReturnData End FunctionPub
6、lic Function CalCRC16Tbl(data() As Byte, no As Integer, btLoCRC As Byte, btHiCRC As Byte) As String Dim btLoCRC As Byte Dim btHiCRC As Byte btLoCRC = &HFF btHiCRC = &HFF Dim i As Integer Dim iIndex As Long For i = 0 To (no - 1)
7、iIndex = btHiCRC Xor data(i) btHiCRC = btLoCRC Xor GetCRCLo(iIndex) '低位处理 btLoCRC = GetCRCHi(iIndex) '高位处理 Next i Dim ReturnData(1) As Byte ReturnData(0) = btHiCRC 'CRC高位 ReturnData(1) = btLoCRC '
8、CRC低位 CalCRC16Tbl = ReturnDataEnd Function'CRC低位字节值表Function GetCRCLo(Ind As Long) As Byte Get