不然妳接收多少字節符合妳改發下壹尋址命令呢?程序代碼處理難度較高.
實際下位機返回數據包可在其代碼中補壹定其它字節來達到等長,從而使接收代碼變得簡潔.
等長接收數據後可對接收處理清0來等待下次接收.
補充:
假如下位機的返回數據按地址號能確定接收字節長度,下列代碼可實現接收不等長數據,僅供參考:
Private 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) = "00" And Len(strData) = 8 Then
Text1(0).Text = Left(strData, 8)
Call DataClear
ElseIf Left(strData, 2) = "01" And Len(strData) = 10 Then
Text1(1).Text = Left(strData, 10)
Call DataClear
End If
End Select
End Sub
Public Sub DataClear()
MSComm1.OutBufferCount = 0 '清空發送緩沖區
MSComm1.InBufferCount = 0
Text3 = ""
End Sub
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 Sub