CRC 问题高手帮看下!
本人对CRC校验不是很了解!下面我把我的通讯协议发下,大家帮看看!我的这个程序怎么改!
读仪表当前累计
STX地 址DTMCRCCRLF
02 30 31 44 54 4d 32 38 0D 0A
其中:
STX — — 起始符, 02H
秤号 — — 地址2 位。如秤号为01 时, 即: 30H 31H
D — — 44H
T — — 54H
M — — 4DH
CRC — — 校验和,即其前面所有数值相加并转换为十进制, 然后取后两位并转为ASCII 码。( 其中十位在前、个位在后;其他传输数据都是高位在前)
CR — — 回车 0DH
LF — — 换行 0AH
程序里这样用的:
Call Lrc_Fun(SendStr, LRC_TMP, 5)
SendStr(6) = LRC_TMP(0)
SendStr(7) = LRC_TMP(1)
定义的FUN:
Public Function Lrc_Fun(SendStr() As Byte, Lrc_data() As Byte, data_long As Byte)
Dim Lrc_DD As Long
Dim Lrc_byte As Byte
Dim lRC_ll As Byte
Dim Lrc_hl As Byte
Lrc_DD = 0
For i = 0 To data_long Step 2
Lrc_DD = Lrc_DD + AsciiToDec(SendStr(i)) * 16 + AsciiToDec(SendStr(i + 1))
Next i
Lrc_byte = Lrc_DD Mod &H100
Lrc_byte = Not Lrc_byte
Lrc_byte = (Lrc_byte + 1) Mod &H100
lRC_ll = Lrc_byte \ 16
Lrc_hl = Lrc_byte Mod 16
Lrc_data(0) = DecToAscii(lRC_ll)
Lrc_data(1) = DecToAscii(Lrc_hl)
End Function
哪位帮我看看,问题出在哪里!!我试了!校验一直不对!!帮改改!非常感谢!
[解决办法]
Public Function Lrc_Fun(SendStr() As Byte, Lrc_data() As Byte, data_long As Byte) Dim Lrc_DD As Long Dim Lrc_byte As Byte Dim lRC_ll As Byte Dim Lrc_hl As Byte Dim i As Long Lrc_DD = 0 For i = 0 To data_long - 1 Step 2 '多算了一次' Lrc_DD = Lrc_DD + AsciiToDec(SendStr(i)) * 16 + AsciiToDec(SendStr(i + 1)) Next i '既然是按照十进制计算的……' Lrc_byte = Lrc_DD Mod 100 lRC_ll = Lrc_byte \ 10 Lrc_hl = Lrc_byte Mod 10 Lrc_data(0) = DecToAscii(lRC_ll) Lrc_data(1) = DecToAscii(Lrc_hl)End Function
[解决办法]
Private Sub Command1_Click()'初始化一个测试数据 Dim sendstr(10) As Byte sendstr(0) = &H2 sendstr(1) = &H30 sendstr(2) = &H31 sendstr(3) = &H44 sendstr(4) = &H54 sendstr(5) = &H4D sendstr(6) = 0 sendstr(7) = 0 sendstr(8) = &HD sendstr(9) = &HA '计算校验和 Call Lrc_Fun(sendstr, 5)End SubPublic Function Lrc_Fun(ByRef sendstr() As Byte, data_long As Byte) Dim xx As Long, tmp As Long, tmp1 As Long tmp = 0 tmp1 = 0 For xx = 0 To data_long tmp = tmp + sendstr(xx) Next tmp = tmp Mod 100 tmp1 = tmp Mod 10 tmp = tmp \ 10 sendstr(data_long + 1) = 30 + tmp sendstr(data_long + 2) = 30 + tmp1End Function