vb.net中的SerialPort Datareceive - 如何解析收到的数据

时间:2016-09-22 23:54:36

标签: .net vb.net multithreading serialization serial-port

我有一台将串行数据发送到标志的PC。我想要做的是删除标志,并使用.Net程序和另一台PC自行显示。我有一个.Net程序从一个com端口读取数据(从PC到PC的串行电缆) - 读取工作正常,但我不知道如何正确解析我想要的数据,并将其显示在一个标签

以下是目前的工作原理。

  • 计算机将交易信息(价格)发送到com端口。 30秒后,它发送字符串的终止 - 表示我们不再想再显示信息了。

  • 我能够看到这个,包括价格,消息的开头和消息字符的结尾。我在当前.net中收到的数据图片如下。您会注意到它发送01然后价格,在这种情况下2000($ 20.00)。然后在30秒后,它会显示剩余的字符。

enter image description here

这是我的当前代码:

Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Windows.Forms
Imports System.Drawing
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports

Public Class Form1
    Dim myport As Array
    Delegate Sub settextcallback(ByVal [text] As String)
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        'This is the connect button
        SerialPort1.PortName = "COM3" 'Connect on COM3
        SerialPort1.BaudRate = "1200" 'Set BaudRate to 1200
        SerialPort1.Open()
        Button1.Enabled = False


    End Sub

    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
'this is the disconnect button
        SerialPort1.Close()

    End Sub

    Private Sub SerialPort1_DataReceived(sender As System.Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        ReceivedText(SerialPort1.ReadExisting)

    End Sub
    Private Sub ReceivedText(ByVal [text] As String)
'now we display the information
        If Me.RichTextBox1.InvokeRequired Then

            Dim x As New settextcallback(AddressOf ReceivedText)
            Me.Invoke(x, New Object() {(text)})


        Else
            Me.RichTextBox1.Text &= [text]

        End If
    End Sub
End Class

如何解析前导01,在这种情况下只显示20.00美元的标签 - 让我们称之为“label1”,直到收到尾随的'01'。一旦收到尾随'01',我想清除标签。

我试图清除,然后在线程中传输文本框,因为数据一次只有一个 - 这不会给我我想要的结果。

1 个答案:

答案 0 :(得分:1)

我认为这非常强大,但您可以自己解决。

将它放入计时器中,它可以正常工作。

Private Sub TimerPrice_Tick(sender As Object, e As EventArgs) Handles TimerPrice.Tick

Dim output As Array = TextBox1.Text.Split("#")

    If output.Length = 2 Then
        Label1.Text = output(1)
    Else
        Label1.Text = vbNullString
    End If
End Sub