Option Explicit
Dim sj As String
Private Sub Form_Load()
MSComm1.Settings = "9600,n,8,1"
MSComm1.InputMode = comInputModeText
MSComm1.RThreshold = 1 '当接收缓冲区到达1-8字节产生1次OnComm事件
MSComm1.CommPort = 1
MSComm1.PortOpen = True
End Sub
Private Sub MSComm1_OnComm()
Select Case MSComm1.CommEvent
Case 2
sj = sj & MSComm1.Input
If Left(sj, 1) = "A" And Right(sj, 1) = "Z" Then
Text1 = Mid(sj, 2, Len(sj) - 2)
sj = ""
Else
MSComm1.PortOpen = False
sj = ""
MSComm1.PortOpen = True
End If
End Select
End Sub
回复LZ:"还有,真的别让我再用MSComm1_OnComm() 来触发啦,连续快速接收的时候真的会程序假死的!"
这种情况是存在的,就是有线连接串口通信也存在通信假四现象.但也不是不可解决的.
请参阅:
http://topic.csdn.net/u/20080220/23/f8b5fc30-7fd3-4db9-8eb0-0262b87e8089.html
http://topic.csdn.net/u/20071220/21/2dd86b50-2f5d-47b0-b4a9-3b232b493396.html
双击MSCOMM控件进入OnComm,当有数据传输到PC机时就会触发这个事件,所以不需要在Timer中来实时监测。
下面是一个例子可以参考一下:
'*****************************************
'串口处理
'*****************************************
Private Sub MSComm_OnComm()
On Error GoTo hak:
Dim intInputLen As Integer
Dim str As String
Dim temp As Integer
Dim fl As Single
Dim i As Integer
Select Case MSComm.CommEvent
Case comEvReceive
RX = RX + 1
StatusBar1.Panels(4).Text = "接收:" & RX
intInputLen = MSComm.InBufferCount '是指调制解调器已接收,并在接收缓冲区等待被取走的字符数。
ReDim inbyte(intInputLen) ' 重新定义数组长度
inbyte = MSComm.Input
'按字符接收
If OpType(0).Value = True Then
For i = LBound(inbyte) To UBound(inbyte)
str = str + Chr(inbyte(i))
Next i
txtReceive.Text = txtReceive.Text & str
'十六进接收
ElseIf OpType(1).Value = True Then
For i = LBound(inbyte) To UBound(inbyte)
str = str + CStr(Hex(inbyte(i))) + Chr(32)
If Len(Hex(inbyte(i))) <= 1 Then
txtReceive.Text = txtReceive.Text & "0" & str
Else
txtReceive.Text = txtReceive.Text & str
End If
Next i
'整型接收
ElseIf OpType(2).Value = True Then
Dim bit As Byte
bit = inbyte(0)
For i = LBound(inbyte) To UBound(inbyte)
temp = temp + CLng(inbyte(i))
Next i
If bit >= 128 Then '判断是否为负
txtReceive.Text = txtReceive.Text & (temp - 255) & " "
Else
txtReceive.Text = txtReceive.Text & temp & " "
End If
End If
End Select
MSComm.InBufferCount = 0
hak:
MSComm.InBufferCount = 0
End Sub
只能分时接收了
比如 char rev_buf[1024]
现接收1024个
在循环判断
rev[i]=='A'
rev[i+4]=='Z'
则为有效数字
另外:你的仪器为一台
这种单工通信还行
如果不止一台
则会有干扰
还不如不要上位机
当然 这只是我的想法而已
把comm控件设置为每6个字符激发一次oncomm事件。
这样实时读取就可以了。
用时钟控件也是可以的,定期把缓冲区的数据读出来,
再整理处理。