vb串口收数据
串口设置:
With MSComm1
.CommPort = intCommPort '通信端口号
.Settings = strCommSettings ' "9600,N,8,2" '通信端口参数
.InBufferSize = 24 '缓冲区接收数据长度
.InputMode = comInputModeBinary '端口以二进数据发送
.InputLen = 24 '每次从端口缓冲区读数据的长度
.RThreshold = 24 '接收N个字节就产生Oncomm事件
.PortOpen = True '打开串口
End With
接收事件:
Private Sub MSComm1_OnComm()
Dim InByte, i As Integer
js = ""
Select Case MSComm1.CommEvent
Case 2
InByte = MSComm1.Input
For i = 0 To 23
js = js & Hex(InByte(i)) & " "
data(i) = InByte(i)
AnaData(i) = Hex(InByte(i))
Next
Text2.Text = Len(InByte)
End Select
MSComm1.InBufferCount = 0
Text1.Text = js
AnalyseData
End Sub
现在的问题是收到的数据一般都正常,但也有少数情况收到的不正常,10次有2,3次,正常的都是F2打头的,不正常的就不是以F2打头的,用串口工具接收正常,都是F2打头,不知道表述明白不,求帮助
[解决办法]
不管收到数据长度是多少,你也要自己判断里面的格式.
而且缓冲区长度太短了,那么在你某次处理收到的数据时如果慢了一点点,这个时候设备又有数据发来,就会把缓冲区里的数据顶掉,这样你取到的可能是不正确的数据.
使用默认的1024长度吧.
[解决办法]
看看这个
Option Explicit
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
'接收事件:
Private Sub MSComm1_OnComm()
Dim InByte(0 To 1023) As Integer
Dim i As Integer
Dim j As Integer
Dim varP As Variant
js = ""
Select Case MSComm1.CommEvent
Case 2
MSComm1.RThreshold = 0 '在接收数据时禁止触发OnComm事件
Sleep 10
Do
varP = Null
varP = MSComm1.Input
If Not IsNull(varP) Then
InByte(i) = Val("&H" & varP(0))
i = i + 1
js = js & varP(0) & " "
End If
Loop Until MSComm1.InBufferCount = 0
Text2.Text = Len(InByte)
Text1.Text = js
MSComm1.RThreshold = 1 '接收完毕,恢复触发功能
End Select
End Sub
Private Sub Form_Load()
With MSComm1
.CommPort = intCommPort '通信端口号
.Settings = strCommSettings ' "9600,N,8,2" '通信端口参数
.InBufferSize = 1024 '缓冲区接收数据长度
.InputMode = comInputModeBinary '端口以二进数据发送
.InputLen = 1 '每次从端口缓冲区读数据的长度
.RThreshold = 1 '接收N个字节就产生Oncomm事件
.PortOpen = True '打开串口
End With
End Sub