不然你接收多少字节符合你改发下一寻址命令呢?程序代码处理难度较高.
实际下位机返回数据包可在其代码中补一定其它字节来达到等长,从而使接收代码变得简洁.
等长接收数据后可对接收处理清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
欢迎分享,转载请注明来源:夏雨云
评论列表(0条)