vb mscomm 接收不到数据
Else
buffer = buffer + Hex(inbyte(i)) + Chr(32)
End If
lenbuffer = Len(Replace(Trim(buffer), " ", ""))
Select Case lenbuffer
Case Is = 14
If CByte("&H" & (Mid(Replace(buffer, " ", ""), 1, 2))) = &HAA _
And "&H" & (Mid(Replace(buffer, " ", ""), 14 - 4 + 1, 2)) = &H42 _
And "&H" & (Mid(Replace(buffer, " ", ""), 14 - 2 + 1, 2)) = &H42 Then
If "&H" & (Mid(Replace(buffer, " ", ""), 14 - 12 + 1, 2)) = &H55 Then
If "&H" & (Mid(Replace(buffer, " ", ""), 14 - 10 + 1, 2)) = &H43 _
And "&H" & (Mid(Replace(buffer, " ", ""), 14 - 8 + 1, 2)) = &H47 _
And "&H" & (Mid(Replace(buffer, " ", ""), 14 - 6 + 1, 2)) = &H8A Then
Text2.Text = "测试通过"
End If
End If
End If
case is = 18
....... 省略
End Select
Next i
End Sub
想问下,为什么上位机接收不到数据??? VB mscomm 数据接收
[解决办法]
OnComm事件代码
缺End Select
Next i位置错误
按我在2楼的接收代码,是能接收到数据的。
请降低波特率调试代码,或许USB转RS232线质量有问题导致。
[解决办法]
把收到的数据全部输出来显示,再与发送的数据相比较,看看到底是完全不对,还是顺序不对,还是有缺失,再进行下一步排查.
[解决办法]
应该是上位机代码屏蔽掉了一些数据。
如果你要调试接收是否正常,把你那些判断条件什么的都注释掉,把接收到的所有数据都显示出来。
[解决办法]
将buffer定义为窗体变量
Option Explicit
Dim buffer As String
Private Sub Form_Load()
Dim i As Integer
If MSComm1.PortOpen = True Then
MSComm1.PortOpen = False
End If
MSComm1.CommPort = 1
MSComm1.Settings = "115200,n,8,1"
MSComm1.InputLen = 0
MSComm1.InputMode = comInputModeBinary
MSComm1.InBufferSize = 1024
MSComm1.OutBufferSize = 2048
MSComm1.InBufferCount = 0
MSComm1.OutBufferCount = 0
MSComm1.SThreshold = 0
MSComm1.RThreshold = 1
MSComm1.PortOpen = True '打开COM口
Command2.Enabled = False
End Sub
Private Sub MSComm1_OnComm()
Dim inbyte() As Byte
Dim lenbuffer As Integer
Dim i As Integer
Select Case MSComm1.CommEvent
Case comEvReceive
inbyte = MSComm1.Input
For i = LBound(inbyte) To UBound(inbyte)
If Len(Hex(inbyte(i))) = 1 Then
buffer = buffer + "0" + Hex(inbyte(i)) + Chr(32)
Else
buffer = buffer + Hex(inbyte(i)) + Chr(32)
End If
Next i
Text1 = buffer
lenbuffer = Len(Replace(Trim(buffer), " ", ""))
Select Case lenbuffer
Case Is = 14
If CByte("&H" & (Mid(Replace(buffer, " ", ""), 1, 2))) = &HAA _
And "&H" & (Mid(Replace(buffer, " ", ""), 14 - 4 + 1, 2)) = &H42 _
And "&H" & (Mid(Replace(buffer, " ", ""), 14 - 2 + 1, 2)) = &H42 Then
If "&H" & (Mid(Replace(buffer, " ", ""), 14 - 12 + 1, 2)) = &H55 Then
If "&H" & (Mid(Replace(buffer, " ", ""), 14 - 10 + 1, 2)) = &H43 _
And "&H" & (Mid(Replace(buffer, " ", ""), 14 - 8 + 1, 2)) = &H47 _
And "&H" & (Mid(Replace(buffer, " ", ""), 14 - 6 + 1, 2)) = &H8A Then
Text2.Text = "????"
End If
End If
End If
End Select
End Select
End Sub
接收数据是固定字节长度的话,由于可以设置MSComm1.RThreshold为固定字节长度,buffer定义于为过程变量,接收代码照你原先的是没问题的。
而接收不定长的字节,只能设置MSComm1.RThreshold = 1,而COM口硬件原因,大于8字节以上的数据到达COM口会多次触发OnComm事件,buffer定义于为过程变量会导致接收字节不完整有丢数据现象,所以buffer定义于为全局变量。
[解决办法]
我一般的做法是,收到数据先检查长度,再与已存储的长度相加,看看是不是已经达到我要求的长度.
如果达到或超过,就进入处理流程.
处理流程里会找到有效数据的头与尾,并清空尾部数据以前的数据,保证未处理的数据是在缓冲区开头.
如此周而复始.
[解决办法]
推荐使用portmon软件辅助串口通讯调试。