【 tulaoshi.com - ASP.NET 】
全局参数:Private Rv_data() As Byte '存放接收的数据Private tmpRV() As Byte '存放暂存的数据Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Form_Load ()中先初始化控件参数With MSComm1.Settings = "9600,N,8,1".InputMode = 1 '设置接受数据的类型是二进制类型数据.InputLen = 8 '一次性从接收缓冲区中读取所有数据(8个字节为一组).InBufferCount = 0 '清空接收缓冲区.OutBufferCount = 0 '清空发送缓冲区.SThreshold = 0 '一旦发送数据就触发OnComm()事件来检测是否返回数据.RThreshold = 1 '接收到1个字节数据就立即触发OnComm()事件.CommPort = 1 '使用第一个串口.PortOpen = True '打开串口End With
思路是这样的:按8个为一组然后一组一组地进行取出,直到缓冲区数据全部取完为止Private Sub MSComm1_OnComm()Dim UB1%, UB2%, TM As Integer, i As IntegerSelect Case MSComm1.CommEventCase comEvReceive Sleep (20) '相隔20ms就可以正确接收到24个字节的数据 Do While MSComm1.InBufferCount > 0 TM = TM + 1 If TM = 1 Then Rv_data = MSComm1.Input Else tmpRV = MSComm1.Input UB1 = UBound(Rv_data) UB2 = UBound(tmpRV) + 1 '元素比下标大1 ReDim Preserve Rv_data(UB1 + UB2) For i = UB1 + 1 To UB1 + UB2 Rv_data(i) = tmpRV(i - UB1 - 1) Next i End If LoopIf Check_RvData Then Call Response_OK() '这里用来进行正确的处理Else Call Response_Bad() '这里用来进行错误处理End IfErase tmpRVErase Rv_dataEnd SelectEnd Sub