突破MsComm控件RThreshold限制,全部数据统统收!

类别:.NET开发 点击:0 评论:0 推荐:

全局参数:
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 Integer
Select Case MSComm1.CommEvent
Case 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
    Loop
If Check_RvData Then
       Call Response_OK()               '这里用来进行正确的处理
Else
        Call Response_Bad()             '这里用来进行错误处理
End If
Erase tmpRV
Erase Rv_data
End Select
End Sub

——————————————————————————————————————————————

本文地址:http://com.8s8s.com/it/it41572.htm