简单串口通信测试程序,谁能帮我看看为何不能接收数据,只能发射
问题如题,希望各位多指点,现在孤军作战,身边无可交流之人.
另外,本人也没有什么VB基础,烦请各位耐心指教,让我先通信起来,先谢过了.
Private Sub Command2_Click()
mscomm_init
MSComm1.Output = Chr(Val(Text1.Text))
MSComm1.PortOpen = False
End Sub
Private Sub Option1_Click()
mscomm_init
MSComm1.Output = Chr(&H33)
MSComm1.PortOpen = False
End Sub
Private Sub Option2_Click()
mscomm_init
MSComm1.Output = Chr(&H66)
MSComm1.PortOpen = False
End Sub
Private Sub mscomm_init()
MSComm1.CommPort = 2
If MSComm1.PortOpen = False Then
With MSComm1
.CommPort = 2
.RThreshold = 1 ' 设置触发oncom事件的字节数
.SThreshold = 0
.Settings = "56000,n,8,1"
.InputMode = comInputModeBinary
.PortOpen = True
.InBufferCount = 0 '清空缓存
.OutBufferCount = 0
.InputLen = 1
End With
Else
MSComm1.PortOpen = False
MsgBox ("串口已开启,无法使用")
End If
End Sub
Private Sub Picture1_Click()
Line (0, 9)-(0, 3000)
End Sub
Private Sub MSComm1_OnComm()
Dim a As Byte
Select Case MSComm1.CommEvent
Case comEvReceive
a = MSComm1.Input
End Select
End Sub
Private Sub Form_Load()
MSComm1.CommPort = 2
MSComm1.RThreshold = 1
If MSComm1.PortOpen = True Then
MSComm1.PortOpen = False
End If
Rem MSComm1.PortOpen = True
End Sub
Private Sub 发送数据_Click()
End Sub
[解决办法]
发送时打开COM口后你把COM关闭了,无法接收.MSCOMM控件的属性设置,仅可能用其缺省设置.
Option Explicit Dim strData As StringPrivate Sub Command2_Click() MSComm1.Output = Chr(Val(Text1.Text))End SubPrivate Sub Option1_Click() MSComm1.Output = Chr(&H33)End SubPrivate Sub Option2_Click() MSComm1.Output = Chr(&H66)End SubPrivate Sub mscomm_init() MSComm1.CommPort = 1End SubPrivate Sub Picture1_Click() Line (0, 9)-(0, 3000)End SubPrivate Sub MSComm1_OnComm() Dim a() As Byte Dim i As Integer Select Case MSComm1.CommEvent Case comEvReceive a = MSComm1.Input For i = 0 To UBound(a) If Len(Hex(a(i))) = 1 Then strData = strData & "0" & Hex(a(i)) Else strData = strData & Hex(a(i)) End If Next '以下写符合通信协议规定的判断代码处理接收数据 Text2.Text = strData End SelectEnd SubPrivate Sub Form_Load() MSComm1.CommPort = 1 MSComm1.RThreshold = 1 If MSComm1.PortOpen = False Then With MSComm1 .CommPort = 1 .RThreshold = 1 ' 设置触发oncom事件的字节数 .Settings = "56000,n,8,1" .InputMode = comInputModeBinary '2进制接收 .PortOpen = True .InBufferCount = 0 '清空缓存 .OutBufferCount = 0 .InputLen = 0 End With Else MSComm1.PortOpen = False MsgBox ("串口已开启,无法使用") End IfEnd Sub
[解决办法]
首先 你的问题不属于 COM/DCOM/COM+ 这类
你的程序中 打开串口后 发送数据 然后马上就关闭了这个串口当然接收不到了
还有就是 也没有接收事件啊
Private Sub MSComm1_OnComm() '接收数据
Dim BytReceived() As Byte
Dim strBuff As String
Select Case MSComm1.CommEvent
Case 2
MSComm1.InputLen = 0
strBuff = MSComm1.Input
BytReceived() = strBuff
。。。。。。
这样 就对了