串口的通讯双方都是主动发送的,为什么要在 PC 端设置 Timer 来“接收”。你的接收事务也是应答式的吗,即主机发送命令,从机回送应答数据?你说的“按钮发送数据”是什么意思?根据猜测,你这样试试:1 设置一个全局变量 blnStop As Boolean2 启动Timer 前,设置 blnStop = False3 在你的 Timer 事件中开头加上:DeEvents If blnStop Then Timer1.Enabled = False Exit Sub End If4 当你需要停止 Timer 时,不要对 Timer 直接操作,而是设置 blnStop = True
5 当你意图停止 Timer 后执行某些操作时,先等待 Timer 停止:Do DoEvents If Not Timer1.Enabled Then Exit Do Loop '这里写你的继续操作代码。
按钮单击事件会向串口发送一帧数据,下位机应答结束后,继续执行timer事件采集数据
Private Sub Command3_Click()Dim q As String BL = True Do While Timer1.Enabled DoEvents
Loop q = PLCS("2") Do While Not q = "1" DoEvents Loop Print q BL = False Timer1.Enabled = TrueEnd Sub Private Sub Timer1_Timer() DoEvents If BL Then Timer1.Enabled = False Exit Sub End If
If MDIForm1.MSComm1.PortOpen = True Then Form4.Text1.Text = HEX_to_DEC(PLCR("DM1220", "1")) Form4.Text3.Text = HEX_to_DEC(PLCR("DM1221", "1")) Form4.Text5.Text = HEX_to_DEC(PLCR("DM1220", "1")) Form4.Text7.Text = HEX_to_DEC(PLCR("DM2732", "2")) Form4.Text8.Text = HEX_to_DEC(PLCR("DM700", "1")) Text4.Text = HEX_to_DEC(PLCR("DM2745", "2")) ' Text5.Text = HEX_to_DEC(PLCR("DM2740", "1")) End If End Sub 单击按钮后 数据没有采集了,但是从本地监视看Timer1.Enabled还是为激活的
If blnStop Then
Timer1.Enabled = False
Exit Sub
End If4 当你需要停止 Timer 时,不要对 Timer 直接操作,而是设置 blnStop = True
DoEvents
If Not Timer1.Enabled Then Exit Do
Loop
'这里写你的继续操作代码。
BL = True
Do While Timer1.Enabled
DoEvents
Loop
q = PLCS("2")
Do While Not q = "1"
DoEvents
Loop
Print q
BL = False
Timer1.Enabled = TrueEnd Sub
Private Sub Timer1_Timer()
DoEvents
If BL Then
Timer1.Enabled = False
Exit Sub
End If
If MDIForm1.MSComm1.PortOpen = True Then
Form4.Text1.Text = HEX_to_DEC(PLCR("DM1220", "1"))
Form4.Text3.Text = HEX_to_DEC(PLCR("DM1221", "1"))
Form4.Text5.Text = HEX_to_DEC(PLCR("DM1220", "1"))
Form4.Text7.Text = HEX_to_DEC(PLCR("DM2732", "2"))
Form4.Text8.Text = HEX_to_DEC(PLCR("DM700", "1"))
Text4.Text = HEX_to_DEC(PLCR("DM2745", "2"))
' Text5.Text = HEX_to_DEC(PLCR("DM2740", "1")) End If
End Sub
单击按钮后 数据没有采集了,但是从本地监视看Timer1.Enabled还是为激活的