发表于:2007-03-21 10:09:00
楼主
'做了一个按钮Command,两个文本text1和text2分别显示CRC高位和低位。命令为01 10 00 01 00 01 02 00 00,就是地址为1的安川变频器的故障复位命令。
'正确结果应该是81A7,这个程序算出来是Text1显示34,Text2显示27,请帮忙看看有什么错误。
Private Sub Command_Click()
Dim crc16lo As Byte, crc16hi As Byte 'crc寄存器
Dim cl As Byte, ch As Byte '多项式码&ha001
Dim savehi As Byte, savelo As Byte
Dim i As Integer
Dim flag As Integer
Dim Data(0 To 8) As Byte
Data(0) = 1
Data(1) = 10
Data(2) = 0
Data(3) = 1
Data(4) = 0
Data(5) = 1
Data(6) = 2
Data(7) = 0
Data(8) = 8
crc16lo = &HFF
crc16hi = &HFF
cl = &H1
ch = &HA0
For i = 0 To 8
crc16lo = crc16lo Xor Data(i) '每一个数据与crc寄存器进行异或
For flag = 0 To 7
savehi = crc16hi
savelo = crc16lo
crc16hi = crc16hi \ 2 '高位右移一位
crc16lo = crc16lo \ 2 '低位右移一位
If ((savehi And &H1) = &H1) Then '如果高位字节最后一位为1
crc16lo = crc16lo Or &H80 '则低位字节右移后前面补1
End If '否则自动补0
If ((savelo And &H1) = &H1) Then '如果lsb为1,则与多项式码进行异或
crc16hi = crc16hi Xor ch
crc16lo = crc16lo Xor cl
End If
Next flag
Next i
Text1 = CStr(Hex(crc16hi)) &n