串口通信重复接收相同数据校验和不同!
本帖最后由 qiuming1 于 2010-05-13 12:09:33 编辑 Private Sub MSComm1_OnComm()
Dim intInputLen As Integer
Dim str as string
Select Case MSComm1.CommEvent
Case comEvReceive
MSComm1.InputMode = comInputModeBinary
intInputLen = MSComm1.InBufferCount
ReDim bytInput(intInputLen)
bytInput = MSComm1.Input
jieshou
End Select
Dim i As Integer
Dim decSum As Integer, hexSum As String
For i = 1 To Len(str) - 2 Step 2
decSum = decSum + ("&H" & Mid(str, i, 2))
Next
decSum = decSum And 255
hexSum = Hex(decSum)
If hexSum = Mid(str, 17, 2) Then
MsgBox "正确!", vbInformation, "提示"
else
MsgBox "错误!", vbInformation, "提示"
End if
Public Function jieshou()
Dim i As Integer
For i = 0 To UBound(bytInput)
str = str & Right("0" & Hex(bytInput(i)), 2)
Next
end function
16进制发送 aa5500123456780013
第一次提示正确 第二次发提示错误
我让text1.text=mid(str,17,2)
发现第一次发是13 发完第一次发第二次是39要添加些什么呀!谢了!
[解决办法]
Option Explicit
Dim strSj As String
Private Sub Form_Load()
MSComm1.CommPort = 1
MSComm1.Settings = "9600,n,8,1"
MSComm1.InputMode = comInputModeBinary
MSComm1.RThreshold = 1
MSComm1.PortOpen = True
End Sub
Private Sub MSComm1_OnComm()
Dim bytInput() As Byte
Dim intInputLen As Integer
Dim str As String
Select Case MSComm1.CommEvent
Case comEvReceive
MSComm1.InputMode = comInputModeBinary
intInputLen = MSComm1.InBufferCount
ReDim bytInput(intInputLen)
bytInput = MSComm1.Input
Dim i As Integer
For i = 0 To UBound(bytInput)
strSj = strSj & Right("0" & Hex(bytInput(i)), 2)
Next
If Mid(strSj, 1, 2) = "AA" And Len(strSj) = 18 Then
Dim decSum As Integer
Dim hexSum As String
For i = 1 To Len(strSj) - 2 Step 2
decSum = decSum + ("&H" & Mid(strSj, i, 2))
Next
decSum = decSum And 255
hexSum = Hex(decSum)
If hexSum = Mid(strSj, 17, 2) Then
Label1.Caption = "正确!"
Else
Label1.Caption = "错误!"
End If
strSj = ""
End If
End Select
End Sub
Else
MsgBox "错误!", vbInformation, "提示"
End If
str = ""
End Sub
Public Function jieshou()
Dim i As Integer
For i = 0 To UBound(bytInput)
str = str & Right("0" & Hex(bytInput(i)), 2)
Next
End Function