VB6.0MsComm控件可以利用OnComm事件连续获取来自外设发送的信号。
基于:
1)MsComm控件的RThreshold 属性不为0和恰当的接收代码。
2)使用电脑主板物理COM口或PCI多串口卡上的COM口COM,这样的COM口是全双工的,发送与接收不会冲突。
3)高质量的接收代码和符合通信协议和数据帧规约的接收处理代码。
实例代码:
Private Sub Form_Load()
MSComm1.InputMode = comInputModeBinary '采用二进制传输
MSComm1.InBufferCount = 0 '清空接受缓冲区
MSComm1.OutBufferCount = 0 '清空传输缓冲区
MSComm1.RThreshold = 1 '产生MSComm事件
MSComm1.InBufferSize = 1024
TxtSend = ""
TxtSend = ""
txtReceive = ""
Text2 = ""
End Sub
Private Sub MSComm1_OnComm() '接收数据
Dim strBuff As String
Select Case MSComm1.CommEvent
Case 2
MSComm1.InputLen = 0
strBuff = MSComm1.Input
BytReceived() = strBuff
jieshou
lenInput = Len(strData)
Text2 = lenInput \ 2
'数据处理代码
End Select
End Sub
Public Function 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
txtReceive = strData
End Function
通讯突然停住的有几个原因:
1 串口设置了接收长度产生中断,但长时间内接收缓冲区没达到产生中断的数据;
2 文本框字符串的总长度超过了64k,文本框不再更新;
3 串口参数配置不正确。
试试我下面的程序看还会不会停住吧,我的程序是不间断接收数据的,不会有停住的可能。
Private Sub Command1_Click()
Timer1.Enabled = True
Command1.BackColor = vbGreen
End Sub
Private Sub Command2_Click()
Text1.Text = ""
End Sub
Private Sub Form_Load()
'通讯口初始化:
With MSComm1
.Settings = "9600,n,8,2"
.CommPort = 3
.InputMode = comInputModeBinary
.InBufferCount = 0
.OutBufferCount = 0
.RThreshold = 0
.SThreshold = 0
.PortOpen = True
End With
Text1.Text = ""
End Sub
Private Sub Text1_Change()
If Len(Text1.Text) > 10000 Then Text1.Text = ""
End Sub
Private Sub Timer1_Timer()
'采用轮循法采集数据
Dim inx() As Byte
Dim strTemp As String
Dim strTemp1 As String
Dim ReceivedLen As Integer
Timer1.Enabled = False '关闭定时器
If MSComm1.InBufferCount > 0 Then
ReceivedLen = MSComm1.InBufferCount
inx = MSComm1.Input
For i = 0 To UBound(inx)
strTemp1 = Hex(inx(i))
If Len(strTemp1) > 1 Then
strTemp = strTemp & strTemp1 & " "
Else
strTemp = strTemp & "0" & strTemp1 & " "
End If
Next i
Text1.Text = Text1.Text & Format(Second(Now), "00") & Right(Format(Str(Timer), "0.00"), 3) & " " & strTemp & vbCrLf
Text1.SelStart = Len(Text1.Text)
End If
Timer1.Enabled = True '打开定时器
Label1.Caption = Now()
End Sub
设置 MSComm1.RThreshold 为10
在 OnComm 事件中 处理!
当 RThreshold 为10 时 就接收
详细 请看 MSDN 吧