VB接收下位机发送的数据并取出其中的数据 求大神相助
本帖最后由 skevil 于 2012-12-12 22:15:14 编辑 求助啊,,,,我在下位机发送的是十六进制数给上位机,格式是 FF 01 02 FF 其中FF是表示头尾,中间01 02 是我想提取出来的数据,怎么取出来呃???求大神大师啊...
Private Sub Command1_Click()
MSComm1.PortOpen = True
End Sub
Private Sub Form_Load()
MSComm1.Settings = "9600,n,8,1"
MSComm1.OutBufferSize = 1024
MSComm1.InBufferSize = 1024
MSComm1.InputMode = 1
MSComm1.InputLen = 0
MSComm1.InBufferCount = 0
MSComm1.SThreshold = 1
MSComm1.RThreshold = 1
End Sub
Public Sub MSComm1_OnComm()
Dim bytInput() As Byte
Dim intInputLen As Integer
Dim n As Integer
Dim teststring As String
Dim jieshou() As Integer
Dim buffer As String
Select Case MSComm1.CommEvent
Case comEvReceive
MSComm1.InputMode = 1 '1:二进制方式
intInputLen = MSComm1.InBufferCount
bytInput = MSComm1.Input
For n = LBound(bytInput) To UBound(bytInput) ' 把接收的数据安十六进制格式放入缓冲中
Text1.Text = Trim(Text1.Text) & " " & IIf(Len(Hex$(bytInput(n))) > 1, Hex$(bytInput(n)), "0" & Hex$(bytInput(n)))
'trim()是去除字符串头或尾部的空格,但不包含中间的空格。 IIF( 逻辑表达式 , 表达式1 , 表达式2 )
buffer = buffer + Hex(bytInput(i)) + Chr(32)
Next n
If Len(Trim(Mid(buffer, 1, 2))) = 1 Then
Text2.Text=Text2.Text & Str("0") & Trim(Mid(buffer, 2, 2))
Else
Text2.Text=Text2.Text & Mid(buffer, 1, 2)
End If
End Select
End Sub
我text1 和 text2 的显示是一样的,真心不明白呃,,,我现在只想要text2显示的是01,而不是像text1那样把整串FF 01 02 FF都显示出来,求大神
[解决办法]
1.
MSComm1.RThreshold = 4
2.
Dim bytInput() As Byte
Dim tmp As Variant
Case comEvReceive
intInputLen = MSComm1.InBufferCount
tmp = MSComm1.Input
bytInput = tmp
For n = LBound(bytInput) To UBound(bytInput) ' 把接收的数据安十六进制格式放入缓冲中
If bytInput(n) = &HFF And bytInput(n + 3) = &HFF Then
buffer = buffer & Right("0" & Hex(bytInput(n + 1)), 2) & Right("0" & Hex(bytInput(n + 2)), 2) & " "
n = n + 3
End If
Next n
Text2.Text = buffer