想实现的是要连续读取从机上的值。需要先发一个读的命令再去收取反馈回来的值(10BYTE)。从机从收到命令到发出回应需要至少6MS。
用下面这段程序,我能连续读到数据,但过了几秒,就会停住不动,此时INBUFFERCOUNT里的值少于10BYTE,而且不变化。
跪求,急等
Private Sub Form_Load()
'MSComm1.CommPort = 2
MSComm1.PortOpen = True
MSComm1.InputLen = 0
MSComm1.InputMode = comInputModeBinary
MSComm1.RThreshold = 0
End Sub
Private Sub Timer1_Timer()
Dim inByte() As Byte
Dim z() As Byte
Dim n As Integer
Dim Send(9) As Byte
Dim tes As Byte
Dim strData As String
Send(0) = 2 'write
Send(1) = 1 'adress
Send(2) = &H85 'mode
Send(3) = 0 '3~8 data
Send(4) = 6
If comdirection.ListIndex = 0 Then
Send(5) = Text1.Text * 5 \ 256
Send(6) = (Text1.Text * 5) Mod 256
Else
Send(5) = (65535 - Text1.Text * 5) \ 256
Send(6) = (65536 - Text1.Text * 5) Mod 256
End If
Send(7) = &HB
Send(8) = &HB8
For i = 0 To 8
Send(9) = Send(9) Xor Send(i) '校验
Next i
MSComm1.Settings = "9600,e,8,1"
If MSComm1.PortOpen = False Then
MSComm1.PortOpen = True
End If
Do
DoEvents
'该循环用来检测命令是否全部发送完毕
Loop Until MSComm1.OutBufferCount = 0
MSComm1.Output = Send
Savetime = Timer '记下开始时的时间
While Timer > Savetime + 1 '循环等待
DoEvents '转让控制权,以便让操作系统处理其它的事件。
Wend
Do
DoEvents
Loop Until MSComm1.InBufferCount >= 10
inByte = MSComm1.Input
For n = 0 To UBound(inByte)
If Len(Hex(inByte(n))) = 1 Then
strData = strData & "0" & Hex(inByte(n))
Else
strData = strData & Hex(inByte(n))
End If
Next n
Text2.Text = Mid(strData, 7, 4)
Text3.Text = Mid(strData, 11, 4)
Text4.Text = Mid(strData, 15, 4)
MSComm1.InBufferCount = 0
End Sub
VB6.0MsComm控件可以利用OnComm事件连续获取来自外设发送的信号。
基于:
1)MsComm控件的RThreshold 属性不为0和恰当的接收代码。
2)使用电脑主板物理COM口或PCI多串口卡上的COM口COM,这样的COM口是全双工的,发送与接收不会冲突。
3)高质量的接收代码和符合通信协议和数据帧规约的接收处理代码。
实例代码:
Private Sub Form_Load()