VB6.0 在开发串口时遇到下位机重启或者上电,就接不到数据了

今天在开发一个APP控制串口软件,用的是MSCOMM控件,存在一个问题就是下位机上电或者重启时,APP就接不到数据了,有遇到过的吗?程序如下:
Private Sub Command1_Click()
On Error Resume Next '//屏蔽错误
If MSC.PortOpen = False Then
MSC.CommPort = Combo1.ListIndex + 1
MSC.Settings = "9600,N,8,1"
MSC.RThreshold = 1
MSC.SThreshold = 0
MSC.InBufferSize = 512
MSC.OutBufferSize = 512
MSC.InputLen = 0
MSC.OutBufferCount = 0
MSC.InBufferCount = 0
MSC.PortOpen = True
'T1 = Combo1.ListIndex
Command1.Caption = "关闭串口"
LED.BorderColor = &HFF&
Else

    Dim buffer() As Byte, CharCount As Integer
    CharCount = MSC.InBufferCount
    If CharCount > 0 Then
        ReDim buffer(0 To CharCount - 1)
        MSC.InputLen = CharCount
        buffer = MSC.Input
    End If

    MSC.PortOpen = False

    Command1.Caption = "打开串口"
    LED.BorderColor = &H0&

End If
If Err Then '//如果端口不存在产生错误

    MsgBox "端口无效", 16, "错误提示"
     MSC.PortOpen = False
     Command1.Caption = "打开串口"
       LED.BorderColor = &H0&
Else '//端口存在返回当前端口号
' Command1.Caption = "关闭串口"

' LED.BorderColor = &HFF&

End If

End Sub

Private Sub MSC_OnComm()
On Error Resume Next '//屏蔽错误
Static blIsOnComm As Boolean
If blIsOnComm = True Then Exit Sub

blIsOnComm = True ' 正在执行MSComm11_OnComm,防止重入

If MSC.CommEvent <> comEvReceive Then Exit Sub ' 接收事件
Dim CharCount As Integer
Dim buffer() As Byte
CharCount = MSC.InBufferCount
ReDim buffer(0 To CharCount - 1)
MSC.InputLen = CharCount
buffer = MSC.Input
Dim i As Byte
For i = 0 To CharCount - 1 '数据多放了一位造成的 多一位现象
If receNum > 20 Then
receNum = 0
MsgBox "接收数据大于20个!", 16, "错误提示"
End If
receArray(receNum) = buffer(i)
receNum = receNum + 1
Next i
receTime = 6

'If Err Then '//如果端口不存在产生错误
' MsgBox MSC.CommEvent & " " & receNum, 16, "错误提示"
' Err.Clear

'End If
blIsOnComm = False
End Sub

1个回答

CommEvent 还有其它取值,看看上电/重启时分别是什么值。
然后在代码中进行对应:
A)提示用户,由用户手工点击按钮进行重新连接。
B)开启一个定时器,定时尝试连接。

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐