代码作了修改,串口通信尽量不用MsgBox,会引起程序中断,供参考:
Option Explicit
Dim Right
Dim CardtypeID
Private Sub Form_Load()
'**********
'串口设置
MSComm1.CommPort = 1
MSComm1.Settings = "9600,n,8,1" ''''''''''''''
MSComm1.InputMode = comInputModeBinary
MSComm1.InputLen = 1
MSComm1.Handshaking = comNone
MSComm1.RThreshold = 19 '如果接收字节总长为19字节
'MSComm1.InBufferSize = 19'本句可能是引起报错的原因
If MSComm1.PortOpen = False Then
MSComm1.PortOpen = True
Label1 = "串口1打开成功"
End If
End Sub
Private Sub op_Click()
Right = 1
Dim i As Integer
Dim sent(1) As Byte
sent(0) = &HA
sent(1) = &HA
'For i = 0 To 1
MSComm1.Output = sent()
'Next i
End Sub
Private Sub MSComm1_OnComm()
Select Case MSComm1.CommEvent
Case comEvReceive
Dim buff As Variant
Dim i As Integer
Dim ttt()
Dim Rdata() As Byte
Dim utrt As Long
Dim wrongcase As Integer
MSComm1.Handshaking = comRTS
utrt = MSComm1.InBufferCount '''问题出现处 utrt值与MSComm1.InBufferCount 不一样 出先比较多的情况是utrt=8 'MSComm1.InBufferCount =11
If utrt < MSComm1.InBufferCount Then
Label1 = "请重新刷卡" ', , "提示"
Exit Sub
End If
MSComm1.InputLen = 0
buff = MSComm1.Input
Dim g As Integer
ReDim Rdata(utrt)
For g = 0 To utrt - 1
Rdata(g) = buff(g)
Next g
If Rdata(0) = 123 And Rdata(1) = 123 Then
Right = 0
Label1 = "读卡错误,请放好卡在读一次或卡未被初试化!" ', , "提示"
MSComm1.PortOpen = False
Exit Sub
End If
CardtypeID = CInt(Rdata(1))
End Select
End Sub