这是我要接受的数据:
                   HEX 
                   20 00 00 00 00 00  00 00 00 00 00 00 67 82 21 00 00 00
                   00 00 00 00 00 00 00 00 00 00 00 00 00 F3 5F 22 00 00 
                   00 00 00 00 00 00 00 00 00 00 00 23 00 00 00 00 00 00 
                   ..............24................25.......等等.
            
    要求:  必须接收20 后面的 10 个字节的数据. 然后在接收21 后面的10个字节.
           然后接收22后面的8个字节,后面的字节不一定是一样的.
           但是这些数据都是一起通过COM口发过来的.
           然后把接收到的字节放到变量里,以后好取出来用.
    各位帮个忙吧.

解决方案 »

  1.   

    你可参考下列代码的做法。
        但建议地址加数据字节长固定,便于正确接收处理,如数据不等长可在下位机上作补长处理:
    Private Sub Form_Load()
        MSComm1.CommPort = 1                   'COM端口
        MSComm1.Settings = "9600,n,8,1"
        MSComm1.InputMode = comInputModeBinary      '采用二进制传输
        MSComm1.InBufferCount = 0   '清空接受缓冲区
        MSComm1.OutBufferCount = 0  '清空传输缓冲区
        'MSComm1.SThreshold = 1      '如果传输缓冲区完全空时产生MSComm事件
        MSComm1.RThreshold = 1      '不产生MSComm事件
        MSComm1.PortOpen = True
        Text3 = "" '打开端口
    End SubPrivate Sub MSComm1_OnComm()
    On Error Resume Next
        Dim BytReceived() As Byte
        Dim strBuff As String
        Dim strData As String
        Dim i As Integer
        Dim x As Integer
        Select Case MSComm1.CommEvent
            Case 2
                MSComm1.InputLen = 0
                strBuff = MSComm1.Input
                BytReceived() = strBuff
                For i = 0 To UBound(BytReceived)
                    If Len(Hex(BytReceived(i))) = 1 Then
                        strData = strData & "0" & Hex(BytReceived(i))
                    Else
                        strData = strData & Hex(BytReceived(i))
                    End If
                Next
                Text3 = Text3 + strData
                If Left(strData, 2) = "20" And Len(strData) = 22 Then
                Text1(0).Text = Left(strData, 22)
                Call DataClear
                ElseIf Left(strData, 2) = "21" And Len(strData) = 22 Then
                Text1(1).Text = Left(strData, 10)
                Call DataClear
                End If
    End Select
    End SubPublic Sub DataClear()
        MSComm1.OutBufferCount = 0   '清空发送缓冲区
        MSComm1.InBufferCount = 0
        Text3 = ""
    End Sub