这几天正在使用VB写一个通过串口的方式实现ModBus协议通讯的小程序,结果发现在接收数据时总是出现问题,感觉很怪异,关键代码如下:打开串口前的初始化设置
MSComm1.CommPort = 3
MSComm1.Settings = "19200,e,8,1"
MSComm1.InputMode = 0
发送前做的设置
MSComm1.InBufferCount = 0
MSComm1.OutBufferCount = 0
MSComm1.Output = hexchrgroup此处我使用一个定时器延时的方法来触发下面的接收程序
接收程序代码
    Dim Hexchr As String, hexstring As String, i As Integer, j As Integer, hexdisp As String
    Dim aa() As Byte
    Dim tempstr As String    Label24.Caption = Str(MSComm1.InBufferCount)    hexstring = MSComm1.Input    If Err Then                                                          '显示出错信息
        MsgBox Error$, 48, "错误信息"
        Exit Sub                                                            '十六进制显示
    End If    i = Len(hexstring)
    tempstr = ""
    For j = 1 To i
        Hexchr = Mid(hexstring, j, 1)
        If Asc(Hexchr) < 16 Then
           tempstr = tempstr & "0" & Hex(Asc(Hexchr)) & " "
        Else
           tempstr = tempstr & Hex(Asc(Hexchr)) & " "
        End If
    Next j
    text1.text = tempstr另外接收到的数据也有问题
发送的数据:01 06 0001 0002 59 CB
接收的数据:01 06 00 01 00 02 59 00

解决方案 »

  1.   

    不明白LZ为何不使用OnComm事件完成接收:
    Option Explicit
        Dim tempstr As String
    Private Sub Form_Load()
        MSComm1.CommPort = 3
        MSComm1.Settings = "19200,e,8,1"
        MSComm1.InputMode = comInputModeBinary
        MSComm1.InBufferCount = 0
        MSComm1.OutBufferCount = 0
        MSComm1.RThreshold = 1
        MSComm1.PortOpen = True
    End SubPrivate Sub MSComm1_OnComm()
        Dim aa() As Byte
        Dim j As Integer
        Select Case MSComm1.CommEvent
            Case 2
            Label1.Caption = Str(MSComm1.InBufferCount)
            aa = MSComm1.Input
            For j = 0 To UBound(aa)
                  tempstr = tempstr & Right("0" & Hex(aa(j)), 2) & " "
            Next j
            Text1.Text = tempstr
        End Select
    End Sub
      

  2.   

    LZ采用ASCII接收,那只能正确处理ASC值在0-127的ASCII字符.我在1楼的代码基于2进制接收,使用OnComm事件接收.