为何无法触发mscomm事件请大家帮忙看看
我将pc两com口相连想通过如下程序实现通信.comsent用来向com1口发送数据,comreceive用来从com2口接收数据.但就是无法触发comreceive的oncomm事件,无法接收数据.请大家看看是怎么回事,是我这种方法根本无法实现啊,还是程序本身有问题,请大家指教
Private Sub cmdsent_Click()
Dim strsent As String
strsent = Trim(txtsent.Text)
If (strsent = " ") Then
MsgBox "发送数据不能为空! ", vbOKOnly, "提示 "
txtsent.SetFocus
Else
comsent.Output = strsent
MsgBox "已经执行发送! ", vbOKOnly, "提示 "
End If
End Sub
Private Sub comreceive_OnComm()
MsgBox "收到数据! "
txtreceive.txt=comreceive.input
End Sub
Private Sub Form_Activate()
With comsent
.InBufferSize = 5120
.CommPort = 1
.Settings = "4800,N,8,1 "
.InputLen = 1
.InputMode = comInputModeText
.RThreshold = 0
.PortOpen = True
End With
With comreceive
.InBufferSize = 5120
.CommPort = 2
.Settings = "4800,N,8,1 "
.InputLen = 1
.InputMode = comInputModeText
.RThreshold = 0
.PortOpen = True
End With
End Sub
[解决办法]
你的代码中的
MsgBox "已经执行发送! ", vbOKOnly, "提示 "
语句中断了接收事件,应删除。
下列代码中改动2处,一是设置comreceive属性RThreshold为1,设置0则不触发OnComm时间中接收。二是不设置comreceive属性InputLen,以便有接收事件发生则全部接收。
Private Sub Form_Activate()
With comsent
.InBufferSize = 5120
.CommPort = 1
.Settings = "4800,N,8,1 "
.InputLen = 1
.InputMode = comInputModeText
.RThreshold = 0
.PortOpen = True
End With
With comreceive
.InBufferSize = 5120
.CommPort = 2
.Settings = "4800,N,8,1 "
'.InputLen = 1
.InputMode = comInputModeText
.RThreshold = 1
.PortOpen = True
End With
End Sub
------解决方案--------------------
对,MSGBOX必须要删除,还要检查你的串口连接线,是你自己做的还是买的?
[解决办法]
RThreshold这个属性是不能为0 的,不然就不能触发OnComm事件,一般设的值为你所接收的数据长度(个人看法)
还有如果PC与设备没有联上,(即设备没有回应),则不会触发OnComm事件
[解决办法]
COM1与COM2的接线,用RS232口,9脚.
2脚与此3脚交叉互接,5脚与5脚对接.
每个RS232接头自身4与6,7与8连接.
[解决办法]
Private Sub comreceive_OnComm()
Dim 串口接收数据 As String
Dim SData As String
Select Case comreceive.CommEvent
'/*==接受信号
Case comEvReceive '
串口接收数据 = MSComm1.Input
SData = 串口接收数据
End Select
End Sub
注意加入CommEvent事件选择,可能OnComm事件发生不代表是收到正确数据。