在实时VB.net中从serialport接收数据

时间:2018-04-17 15:19:23

标签: wpf vb.net synchronization real-time

我创建了此代码以从串口(com)接收数据

 Private port As New SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)

Function ReceiveSerialData() As String

    Dim returnStr As String = ""

    Dim com1 As IO.Ports.SerialPort = Nothing
    Try

        port.Open()

        port.ReadTimeout = 1000

        Dim Incoming As String

            Incoming = port.ReadLine()

        returnStr = Incoming

    Catch erreur As IOException
        returnStr = "Check Port"
    Catch ex As TimeoutException
        returnStr = "Error: Serial Port read timed out."
    Finally
        If port IsNot Nothing Then port.Close()
    End Try

    Return returnStr
End Function



Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded

    Label2.Content = ReceiveSerialData()

End Sub

我希望创建一个事件,以便在数据实时更改时重新执行此代码。

我的表格是这样的: enter image description here

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

嗯,您可以随时使用评论中提到的某种形式的Do While True。不理想,但......

这是您的代码的修改版本,以将读取部分包含在不同的线程中。当它读取内容时,它会引发您可以订阅的事件(或者您可以在阅读后直接将文本放在控件中)。端口始终保持打开状态,因此在此示例中,窗口关闭时将关闭。

试一试,看看它是否适合你。

Private port As New SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)
Private rdthread As System.Threading.Thread
Event PortData(ByVal Message as String)

Private Sub readPort()
    Do While True
        Try
            Dim message As String = port.ReadLine()
            RaiseEvent PortData(message)
            System.Threading.Thread.Sleep(0)
            My.Application.DoEvents()
        Catch ex As Exception
            Exit Do
        End Try
    Loop
End Sub    

Private Sub HandleData(ByVal message as string) Handles Me.PortData
    Label2.Content = message
End Sub

Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
    InitPort()
End Sub

Private Sub Window_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    Try
        If port.IsOpen Then port.Close()
    Finally
        port.Dispose()
    End Try
End Sub 

Sub InitPort() 
    Dim com1 As IO.Ports.SerialPort = Nothing
    Try
        port.Open()
        port.ReadTimeout = 1000

        rdthread = New System.Threading.Thread(AddressOf readPort)
        rdthread.Start()

    Catch erreur As IOException
        returnStr = "Check Port"
    Catch ex As TimeoutException
        returnStr = "Error: Serial Port read timed out."
    Catch ex as Exception

    End Try
End Sub