缓冲串口数据

时间:2014-07-16 20:18:17

标签: vb.net serial-port

我是编程新手,很难在VB .NET中完成我的项目。我正在创建一个测试直流电机的应用程序。我将电机连接到开发板,每隔1秒通过串行端口向我发送电机数据。传入数据的片段如下所示(它来自6行数据; 0到5可以在第二列中看到):

-2 0 234 282 129 749 6232 1013 2430 1889 219 3630

-2 1 112 309 228 959 557 2073 2376 1909 226 3855

-2 2 62 280 78 937 273 2287 2553 1981 234 3938

-2 3 257 86 284 2013 258 885 2640 1931 241 3926

-2 4 202 85 119 642 68 1015 2725 1871 249 3938

-2 5 111 77 222 2315 0 696 2741 1948 256 4110

由于通过串行传输的数据可能是完整的或部分的,我想创建一个滚动缓冲区,以便我可以处理完整的数据集。我没有该消息的任何开始或结束字符/指示符。你能帮忙吗?

这是我的代码的一部分:我也将收到的数据写入文本文件。

Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
    Try
        SW = New StreamWriter(newFileName)

        ReceivedText(SerialPort1.ReadExisting()) 'Automatically called every time a data is received at the serialPort

        SW.Write(rtbReceived.Text.Replace(",", vbTab))

        For Each Line As String In Split(rtbReceived.Text, ",")

            '*********
            'Process Data
            '*********

        Next

        SW.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub

'******************************************************************
'******************************************************************

Private Sub ReceivedText(ByVal [text] As String)
    'compares the ID of the creating Thread to the ID of the calling Thread
    If Me.rtbReceived.InvokeRequired Then
        Dim x As New SetTextCallback(AddressOf ReceivedText)
        Me.Invoke(x, New Object() {(text)})
    Else
        Me.rtbReceived.Text &= [text]
    End If

    '*********
    'Display results in text box in application
    '*********
End Sub

'******************************************************************
'******************************************************************

Private Sub rtbReceived_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rtbReceived.TextChanged
    rtbReceived.SelectionStart = rtbReceived.TextLength
    rtbReceived.ScrollToCaret()
End Sub

此代码的一个问题是" all"每次接收到新数据时都会处理rtbReceived文本框中的数据,类似地,文本文件会删除旧数据并从rtbReceived文本框中写入整个数据。正如我所说的,我不是程序员,所以这段代码可能还有很多其他问题。任何帮助将不胜感激。如果有混淆,请随时提问。

谢谢!

0 个答案:

没有答案