VB6.0串口设计问题
本帖最后由 Java_Devil 于 2012-12-31 14:49:25 编辑 我现在有这样一个需求。连接上一个特定的设备之后。有一个按钮。点击以后从1到40循环所有的串口号。在打开之后。发送一个命令。如果串口号可用。设备才会返回数据。这时候跳出循环就可以了。如果不可用 继续循环。但是我现在发现应该是接收返回数据需要时间吧。循环太快。判断不到返回数据。只有debug时才能正常判断。我用sleep timer都试过了。也没预期的效果。、
Private Sub Command4_Click()
Dim saveTimer As Single
Dim flag As Integer
Dim sj(0 To 1) As Byte
sj(0) = &H1
sj(1) = &H4
Text1.Text = "begin"
For i = 0 To 5
On Error Resume Next
saveTimer = Timer
MSComm1.CommPort = i
MSComm1.Settings = "9600,n,8,1"
MSComm1.PortOpen = True
MSComm1.Output = sj
MSComm1.InputLen = 0
While Timer < saveTimer + 2
DoEvents
strBuff = MSComm1.Input
If (strBuff <> Null Or strBuff <> "") Then
Text1.Text = strBuff
Exit For
Else
Text2.Text = i + "不可用"
MSComm1.PortOpen = False
End If
Wend
Next i
End Sub
saveTimer = Timer
With MSComm1
.CommPort = i
.Settings = "9600,n,8,1"
.InputLen = 0
.PortOpen = True
.Output = sj
While Timer < saveTimer + 2
DoEvents
Sleep 100
If .InBufferCount > 0 Then
Text1 = Text1 & vbCrLf & .Input
Exit For
Else
Text2.Text = Text2 & vbCrLf & CStr(i) + "不是匹配的端口,没有数据返回"
.PortOpen = False
End If
Wend
End With
NextPort:
Next i
Exit Sub
ErrHandler:
Text2.Text = Text2.Text & vbCrLf & CStr(i) & Err.Description
Resume NextPort
End Sub