7,763
社区成员
发帖
与我相关
我的任务
分享
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
Private Sub Timer1_Timer()
Call YourFun(True)
End Sub
Dim cmd_retValue As Long
Dim cmd_IsReturn As Boolean
Dim cmd_Index As Long
Function 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_retValue
End Function
Private 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 If
End Sub
'以下是等待执行
Do
Doevent
Loop While cmd_IsReturn = True
' 也可以换成会略执行
' If cmd_IsReturn = True Then Exit Function
Dim cmd_retValue As Long
Dim cmd_IsReturn As Boolean
Dim cmd_Init As Boolean
Dim cmd_Index As Long
Sub Form1_Load()
cmd_IsReturn = False
cmd_Init = False
On Error Resume Next
' 初始化串口过程,如果失败 直接退出该过程
'.......
cmd_Init = True
End Sub
Function YourFun1(ByVal State As Boolean) As Long
If cmd_Init = False Exit Function
'以下是等待执行
Do
Doevent
Loop While YourFun1=True
' 也可以换成会略执行
' If YourFun1=True Then Exit Function
cmd_IsReturn = False
cmd_retValue = 0
cmd_Index = 1
MSComm1.Output = "CMD1+" & State & vbCr
Do
Doevents
Loop while cmd_IsReturn = False
cmd_Index = 0
YourFun1 = cmd_retValue
End Function
Function YourFun2(ByVal State As Boolean) As Long
If cmd_Init = False Exit Function
'以下是等待执行
Do
Doevent
Loop While YourFun1=True
' 也可以换成会略执行
' If YourFun1=True Then Exit Function
cmd_IsReturn = False
cmd_retValue = 0
cmd_Index = 2
MSComm1.Output = "CMD2+" & State & vbCr
Do
Doevents
Loop while cmd_IsReturn = False
cmd_Index = 0
YourFun2 = cmd_retValue
End Function
Private Sub MSComm1_OnComm()
If MSComm1.CommEvent = comEvReceive Then
ReadStr = MSComm1.Input
Select Case cmd_Index
Case 1:
If ReadStr = "CMD1 OK" Then
cmd_retValue = 1
Else
cmd_retValue = 0
End If
cmd_IsReturn = True
Exit Sub
Case 2:
If ReadStr = "CMD2 OK" & vbCr Then
cmd_retValue = 1
Else
cmd_retValue = 0
End If
cmd_IsReturn = True
Exit Sub
End Select
End If
End Sub
Private Sub Timer1_Timer()
Timer1.Enabled = False
Call YourFun1(True)
Timer1.Enabled = True
End Sub
Private Sub Command1_Click()
Call YourFun2(True)
End Sub