为什么我获取串口数据时有时会乱了呢?
代码如下。我用timer 每1秒分别向下位机获取X Y坐标,但有时数据会少一个位,有时X,Y值会掉转
另:为什么我不用事件触发呢?主要是除了这个命令 我对下位机还有其他命令,我想发一条命令就准确收到其值
我已经不用DOevents了,还会这样
下位机反映速度不用怀疑,都是毫秒级的
- VB code
MSComm1.Output = "AXI1:POS?" & Chr(13) '对下位机发送位置请求 Dim t As Single t = Timer Do 'DoEvents GetInput = MSComm1.Input Loop Until GetInput <> "" Or Timer - t > 1 '主要是防止超时导致的死循环 Labelpos.Caption = GetInput '把位置显示出来 MSComm1.Output = "AXI2:POS?" & Chr(13) t = Timer Do 'DoEvents GetInput = MSComm1.Input Loop Until GetInput <> "" Or Timer - t > 1 Labelposy.Caption = GetInput
[解决办法]
你可以用Timer触发输出过程,但不要在Timer里处理接收过程,接收过程需要在串口事件里处理,如果你想做函数等待结果返回,可以设置一个公共变量作为返回状态判断值,在串口事件里完成接收判断过程后设置这个值你的那个过程就可以返回了,如:
- VB code
Dim cmd_retValue As LongDim cmd_IsReturn As BooleanDim cmd_Index As LongFunction YourFun(ByVal State As Boolean) As Long cmd_IsReturn = False cmd_retValue = 0 cmd_Index = 1 MSComm1.Output = "AXI1:POS?" & vbCr '...... Do Doevents Loop while cmd_IsReturn = False cmd_Index = 0 YourFun = cmd_retValueEnd FunctionPrivate Sub MSComm1_OnComm() If MSComm1.CommEvent = comEvReceive Then ReadStr = MSComm1.Input Select Case cmd_Index Case 1: If UCase(ReadStr) = "+OK" & vbCr Then cmd_retValue = 1 cmd_IsReturn = True End If '...... End Select End IfEnd Sub
[解决办法]
可以用查询方式,但你的查询有问题。假定这个命令的返回是 4 字节:
MSComm1.Output = "AXI1:POS?" & Chr(13) '对下位机发送位置请求
Dim t As Single
t = Timer
Do
DoEvents
Loop Until MSComm1.InBufferCount >= 4 Or Timer - t > 1 '主要是防止超时导致的死循环
GetInput = MSComm1.Input
Labelpos.Caption = GetInput '把位置显示出来