vb串口接收数据问题
我用串口调试工具测试下位机传输的数据正确,现在我自己写了个VB测试程序,发现只能接收到第一个数据,后面全是0不知道为什么,
Select Case MSComm1.CommEvent
Case comEvReceive
ReDim out(1) As Byte
var = MSComm1.Input
out(0) = var(0)
If out(0) = &H7C Then
Numflag = True
' MSComm1.InBufferCount = 0
MSComm1.RThreshold = 0
End If
If out(0) = &H7E Then
Dataflag = True
' MSComm1.InBufferCount = 0
MSComm1.RThreshold = 0
End If
If out(0) = &H0 Then
MSComm1.InBufferCount = 0
MSComm1.RThreshold = 0
MsgBox ( "数据越限 ")
End If
If Numflag = True Then
ReDim out(3) As Byte
' var = MSComm1.Input
' out(1) = var(0)
' var = MSComm1.Input
' out(2) = var(0)
' var = MSComm1.Input
' out(3) = var(0)
For i = 1 To 3
var = MSComm1.Input
out(i) = var(0)
Next
End If
If Dataflag = True Then
ReDim out(56) As Byte
For i = 1 To 55
var = MSComm1.Input
out(i) = var(0)
bb = bb + out(i)
Next
var = MSComm1.Input
out(55) = var '校验位
If out(55) = bb Then
MsgBox ( "数据接收成功! ")
Else
MsgBox ( "数据接收错误! ")
End If
End If
End Select
协议是这样的,我发7E547F去下位机,发7C3030317D给我,我发7E000102F下去,下位机回55个数据给我,现在是我都只能接收到帧头7C或者7E后面的全是0,是怎么回事呢,救命啊~~~~~~~
[解决办法]
下列代码执行一个循环
Option Explicit
Dim BytReceived() As Byte
Dim strdata As String
Dim lenInput As Integer
Dim LblJieshou As String
Private Sub Form_Load()
MSComm1.InputMode = comInputModeBinary
MSComm1.RThreshold = 5 '采用二进制传输
MSComm1.PortOpen = True
End Sub
Private Sub MSComm1_OnComm()
On Error Resume Next
Dim strBuff As String
Text1 = " "
Select Case MSComm1.CommEvent
Case 2
MSComm1.InputLen = 0
strBuff = MSComm1.Input
BytReceived() = strBuff
jieshou
LblJieshou = Text1
Text3 = Len(LblJieshou) \ 2
'数据处理代码
If Mid(LblJieshou, 1, 2) = "7C " And Len(LblJieshou) = 10 Then
Text2 = LblJieshou
MSComm1.RThreshold = 55
Txtsend = "7E000102F "
Call cmdSend_Click
ElseIf Len(LblJieshou) = 110 Then
Text4 = LblJieshou
Text5 = Len(Text4)
End If
strdata = " "
End Select
End Sub
Private Sub cmdSend_Click()
Dim sj() As Byte
Dim sj_Txt As String
Dim i As Integer
sj_Txt = Txtsend
ReDim sj(Len(sj_Txt) / 2 - 1)
For i = 0 To Len(sj_Txt) - 1 Step 2
sj(i / 2) = Val( "&H " & Mid(sj_Txt, i + 1, 2))
Next
If MSComm1.PortOpen = True Then
MSComm1.Output = sj
Else
MSComm1.PortOpen = True
MSComm1.Output = sj
End If
End Sub
Public Sub jieshou() '接收处理为16进制
Dim i As Integer
For i = 0 To UBound(BytReceived)
If Len(Hex(BytReceived(i))) = 1 Then
strdata = strdata & "0 " & Hex(BytReceived(i))
Else
strdata = strdata & Hex(BytReceived(i))
End If
Next
Text1 = strdata
End Sub