none
串口监听问题 RRS feed

  • 问题

  •  

     

     

        Public Partial Class Form1

            Inherits Form

            Public Sub New()

                InitializeComponent()

            End Sub

           

            Private Sp As New SerialPort()

            Public Delegate Sub HandleInterfaceUpdataDelegate(ByVal text As String)

            '委托,此为重点

            Private interfaceUpdataHandle As HandleInterfaceUpdataDelegate        

            Private qiii As Boolean = False      

            Private Sub btENT_Click(ByVal sender As Object, ByVal e As EventArgs)

                If (cmID.Text.Trim() <> "") AndAlso (cmRate.Text <> "") Then

                    interfaceUpdataHandle = New HandleInterfaceUpdataDelegate(UpdateTextBox)

                    '实例化委托对象

                    Sp.PortName = cmID.Text.Trim()

                    Sp.BaudRate = Convert.ToInt32(cmRate.Text.Trim())

                    Sp.Parity = Parity.None

                    Sp.StopBits = StopBits.One

                    AddHandler Sp.DataReceived, AddressOf Sp_DataReceived

                    Sp.ReceivedBytesThreshold = 1

                    Try

                        Sp.Open()

                       

                        ATCommand3("AT+CLIP=1" & vbCr, "OK")                     

                        btPause.Enabled = True

                        btENT.Enabled = False

                    Catch

                        MessageBox.Show("端口" & cmID.Text.Trim() & "打开失败!")

                    End Try

                Else

                    MessageBox.Show("请输入正确的端口号和波特率!")

                    cmID.Focus()

                   

                End If

            End Sub      

            Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)

                GetComList()               

                btPause.Enabled = False

            End Sub

           

            Public Sub Sp_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)

                Dim strTemp As String = ""

                Dim iSecond As Double = 0.5

               

                Dim dtOld As DateTime = System.DateTime.Now

                Dim dtNow As DateTime = System.DateTime.Now

                Dim dtInter As TimeSpan

                dtInter = dtNow - dtOld

               

                Dim i As Integer = Sp.BytesToRead

                If i > 0 Then

                    Try

                        strTemp = Sp.ReadExisting()

                    Catch

                    End Try

                    If strTemp.ToLower().IndexOf(vbCr) < 0 Then

                        i = 0

                    Else

                        Me.Invoke(interfaceUpdataHandle, strTemp)

                    End If

                End If

                While dtInter.TotalSeconds < iSecond AndAlso i <= 0

                    dtNow = System.DateTime.Now

                    dtInter = dtNow - dtOld

                    i = Sp.BytesToRead

                    If i > 0 Then

                        Try

                            strTemp += Sp.ReadExisting()

                        Catch

                        End Try

                        If strTemp.ToLower().IndexOf(vbCr) < 0 Then

                            i = 0

                        Else

                            Me.Invoke(interfaceUpdataHandle, strTemp)

                        End If

                    End If

                    ' do null

                   

                End While

            End Sub

           

            Private Sub UpdateTextBox(ByVal text As String)

                tbData.Text = text

            End Sub

            Private Sub ATCommand3(ByVal ATCmd As String, ByVal StCmd As String)

                Dim response As String = ""                

                response = ATCommand(ATCmd, StCmd)

            End Sub

           

            Private Function ATCommand(ByVal ATCmd As String, ByVal StCmd As String) As String

                Dim response As String = ""

                Dim i As Integer

                If Not ATCmd.EndsWith(ChrW(26)) Then

                    If Not (ATCmd.EndsWith(vbCr) OrElse ATCmd.EndsWith(vbCr & vbLf)) Then

                        ATCmd = ATCmd & vbCr

                    End If

                End If

                Sp.WriteLine(ATCmd)

               

                '第一次读响应数据

                If Sp.BytesToRead > 0 Then

                    response = Sp.ReadExisting()

                   

                    '去除前端多可能多读取的字符

                    If response.IndexOf(ATCmd) > 0 Then

                        response = response.Substring(response.IndexOf(ATCmd))

                    Else

                       

                    End If

                   

                    If response = "" OrElse response.IndexOf(StCmd) < 0 Then

                        If response <> "" Then

                            If response.Trim() = "ERROR" Then

                                'throw vError = new UnknowException("Unknown exception in sending command:" + ATCmd);

                            End If

                            If response.IndexOf("+CMS ERROR") >= 0 Then

                                Dim cols As String() = New String(99) {}

                                cols = response.Split(";"c)

                                If cols.Length > 1 Then

                                    Dim errorCode As String = cols(1)

                                End If

                            End If

                        End If

                    End If

                End If

               

                '读第一次没有读完的响应数据,直到读到特征数据或超时

                For i = 0 To 2

                    Thread.Sleep(1000)

                    response = response + Sp.ReadExisting()

                    If response.IndexOf(StCmd) >= 0 Then

                        Exit For

                    End If

                Next

               

                   

                   

                Return response

            End Function

     

     

            Private Sub GetComList()

     

                Dim keyCom As RegistryKey = Registry.LocalMachine.OpenSubKey("Hardware\DeviceMap\SerialComm")

                If keyCom IsNot Nothing Then

                    Dim sSubKeys As String() = keyCom.GetValueNames()

                    Me.cmID.Items.Clear()

                    For Each sName As String In sSubKeys

                        Dim sValue As String = DirectCast(keyCom.GetValue(sName), String)

                        Me.cmID.Items.Add(sValue)

                    Next

                End If

            End Sub

           

            Private Sub cmID_DropDown(ByVal sender As Object, ByVal e As EventArgs)

                GetComList()

            End Sub

           

        End Class


    为什么tbData的text中没有任何东西????

    2009年9月17日 8:50

答案

  • 你好!
         你的tbData变量是什么,从你的代码中没有发现他的定义!
    周雪峰

    tbData应该是一个TextBox控件


    回复楼主:

    你需要检查几个地方:
    If (cmID.Text.Trim() <> "") AndAlso (cmRate.Text <> "") Then

                    interfaceUpdataHandle = New HandleInterfaceUpdataDelegate(UpdateTextBox)

                    '实例化委托对象

    这里只有当cmID和cmRate都有值时才会实例化委托,不过这里应该没问题

    SerialPort.ReadExisting是读取改对象的的流的内容和写入到缓冲区的内容
    即便是读取到数据 但是如果读取到回车符的话 那么也不会引用委托,即不会对tbData进行赋值,这里应该是你的问题的所在
    If strTemp.ToLower().IndexOf(vbCr) < 0 Then

                        i = 0

                    Else

                        Me.Invoke(interfaceUpdataHandle, strTemp)

                    End If


    Wenn ich dich hab’,gibt es nichts, was unerträglich ist.坚持不懈!http://hi.baidu.com/1987raymond
    2009年9月18日 4:59
    版主

全部回复

  • 你好!
         你的tbData变量是什么,从你的代码中没有发现他的定义!
    周雪峰
    2009年9月17日 10:55
    版主
  • 你好!
         你的tbData变量是什么,从你的代码中没有发现他的定义!
    周雪峰

    tbData应该是一个TextBox控件


    回复楼主:

    你需要检查几个地方:
    If (cmID.Text.Trim() <> "") AndAlso (cmRate.Text <> "") Then

                    interfaceUpdataHandle = New HandleInterfaceUpdataDelegate(UpdateTextBox)

                    '实例化委托对象

    这里只有当cmID和cmRate都有值时才会实例化委托,不过这里应该没问题

    SerialPort.ReadExisting是读取改对象的的流的内容和写入到缓冲区的内容
    即便是读取到数据 但是如果读取到回车符的话 那么也不会引用委托,即不会对tbData进行赋值,这里应该是你的问题的所在
    If strTemp.ToLower().IndexOf(vbCr) < 0 Then

                        i = 0

                    Else

                        Me.Invoke(interfaceUpdataHandle, strTemp)

                    End If


    Wenn ich dich hab’,gibt es nichts, was unerträglich ist.坚持不懈!http://hi.baidu.com/1987raymond
    2009年9月18日 4:59
    版主