VB 串口接收不定长数据的实现
PC机接收下位机传送的不定长的十六进制码数据,为什么单步调试的时候数据接收成功,但一自动运行就不行了,接收到数据后面几位会丢掉?WithMSComm1.Settings=...
PC机接收下位机传送的不定长的十六进制码数据,为什么单步调试的时候数据接收成功,但一自动运行就不行了,接收到数据后面几位会丢掉?
With MSComm1
.Settings = "1200,n,8,1"
.RThreshold = 1
.InputLen = 0
.InputMode = comInputModeBinary
.SThreshold = 0
.PortOpen = True
End With
Private Sub MSComm1_OnComm()
'接收到数据:fe fe 68 02 68 1a 04 02 2e 05 06 2b 16
Dim count As Integer, i As Integer
Dim Buffer As Variant
Dim serial() As Byte
Select Case MSComm1.CommEvent
Case comEvReceive
MSComm1.RThreshold = 0 '防止在处理数据时产生OnComm事件
Do While MSComm1.InBufferCount < 9 '一组数据至少9位
DoEvents
Loop
MSComm1.InputLen = 0
Buffer = MSComm1.Input
MSComm1.InBufferCount = 0
For i = LBound(Buffer) To UBound(Buffer)
serial(i) = Buffer(i)
Next i
If Serial_Command_Run(serial()) = True Then
End If
MSComm1.RThreshold = 1 '处理完毕,打开触发
End Select
End Sub 展开
With MSComm1
.Settings = "1200,n,8,1"
.RThreshold = 1
.InputLen = 0
.InputMode = comInputModeBinary
.SThreshold = 0
.PortOpen = True
End With
Private Sub MSComm1_OnComm()
'接收到数据:fe fe 68 02 68 1a 04 02 2e 05 06 2b 16
Dim count As Integer, i As Integer
Dim Buffer As Variant
Dim serial() As Byte
Select Case MSComm1.CommEvent
Case comEvReceive
MSComm1.RThreshold = 0 '防止在处理数据时产生OnComm事件
Do While MSComm1.InBufferCount < 9 '一组数据至少9位
DoEvents
Loop
MSComm1.InputLen = 0
Buffer = MSComm1.Input
MSComm1.InBufferCount = 0
For i = LBound(Buffer) To UBound(Buffer)
serial(i) = Buffer(i)
Next i
If Serial_Command_Run(serial()) = True Then
End If
MSComm1.RThreshold = 1 '处理完毕,打开触发
End Select
End Sub 展开
1个回答
展开全部
是因为PC接收的带快了远端发送速度跟不上。在每接收一次数据休眠一定时间来同步即可。
不过VB不支持线程,需要导入API:
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
然后在 Do While MSComm1.InBufferCount < 9 '一组数据至少9位
DoEvents
Loop
的DoEvents前加上sleep(50),当然不一定是50,要反复实验确认合适的值
不过VB不支持线程,需要导入API:
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
然后在 Do While MSComm1.InBufferCount < 9 '一组数据至少9位
DoEvents
Loop
的DoEvents前加上sleep(50),当然不一定是50,要反复实验确认合适的值
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询