'电子秤(电子天平)使用RS232C和PC串口进行通讯,本例使用应答型。
'因为要使用DDE来控制此电子秤的开、关,所以加入了一个Timer来读取DDE信息,发现为开
'关信息的时候直接向COM写入相应的信息。 '加入一个1000ms的定时器来定时向COM写入读取信息。
'建立Form,LinkMode-1-Sourse,LinkTopic-自己定义
'MSComm控件-mscommWeight,2个Timer控件-tmrOrderScan(200ms),
'tmrRead(1000ms)
Option Explicit
Private strRecBuf As String
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Sub Form_Activate()
Me.Hide '如果用在实时数据采集上,那么可以选择隐藏此界面
End Sub
Private Sub Form_Load() '设置并打开串口
If mscommWeight.PortOpen = True Then mscommWeight.PortOpen = False
mscommWeight.CommPort = 1 'COM1
If mscommWeight.PortOpen = False Then mscommWeight.PortOpen = True
mscommWeight.Settings = "2400,n,8,1"
mscommWeight.InputLen = 0
mscommWeight.RThreshold = 1
mscommWeight.InputMode = comInputModeText '接收为文本方式
End Sub
Private Sub mscommweight_OnComm()
Select Case mscommWeight.CommEvent '发生OnComm事件
Case comEvReceive '接收到信息
strRecBuf = strRecBuf & mscommWeight.Input '接收信息
Case Else
End Select
If InStr(strRecBuf, "g") Then '发现接收完毕(检测到最后一个标志)
lblWeight.Caption = Mid(strRecBuf, InStr(strRecBuf, ",") + 1, 10) '取数据位
strRecBuf = "" '清除接收变量
End If
End Sub
Private Sub tmrOrderScan_Timer()
DoEvents
Select Case lblSwitch.Caption
Case "Action" '当接收到开关信息时
tmrWeight.Enabled = False '关闭读信息定时器
mscommWeight.Output = Chr(&H50) & Chr(&HD) & Chr(&HA) '发送开关机信息
lblSwitch.Caption = "" '接收信息复位
Sleep 200 '等待200ms
tmrWeight.Enabled = True '重新打开读信息定时器
Case Else
End Select
End Sub
Private Sub tmrWeight_Timer()
mscommWeight.Output = Chr(&H51) & Chr(&HD) & Chr(&HA) '发送读信息
End Sub