VB.net serialport.readline与接收到的数据与线程



新手(非常新手(程序员,在VB.net中工作……我读过很多关于这方面的不同观点,接缝线程是最好的解决方案,但在这一点上我有点不知所措。我试图完成的是从串行端口(蓝牙(读取一行数据。数据的长度始终相同,并且始终以CRLF结尾(数据为ASCII(。我从数字扭矩扳手中读取数据,用户必须用扳手拧紧6个螺栓,每个螺栓通过串行端口发送一系列数据。我读取这些原始数据,并从字符串中提取实际扭矩值,并将其保存到数据库中。我有数据库连接工作,我可以读取数据并提取我需要的值。问题是,如果用户由于某种原因不得不退出阅读,我就无法退出该事件。我尝试添加一个按钮,将变量设置为true(Dim BoolEscape as Boolean设置为"true"(。然后添加了Application.DoEvents((调用,然后检查BoolEscape是否为True,然后退出sub…根据我所读到的内容,这不起作用,也永远不会起作用。

接收到的数据串被格式化为:;RE,001100.0,16/08/20,12:45:10CRLF";

以下是我的BtnStartRead_Click事件中的一些代码。。。我只展示了两个螺栓的价值,因为它只是重复。。。。我相信线程是答案,但同样,我不明白它是如何工作的。。。。

Private Sub btnStartRead_Click(sender As Object, e As EventArgs) Handles btnStartRead.Click
On Error GoTo err_handle
boolEscape = False
txtBolt1.BackColor = Color.FromArgb(255, 255, 128)
txtBolt2.BackColor = Color.FromArgb(255, 255, 128)
txtBolt3.BackColor = Color.FromArgb(255, 255, 128)
txtBolt4.BackColor = Color.FromArgb(255, 255, 128)
txtBolt5.BackColor = Color.FromArgb(255, 255, 128)
txtBolt6.BackColor = Color.FromArgb(255, 255, 128)
lblA1.Visible = True
ShowRXon()
txtRaw1.Text = mySerialPort.ReadLine
ShowRXoff()
txtBolt1.Text = txtRaw1.Text.Substring(7, 4)
If checkValue(txtBolt1.Text) = False Then
txtBolt1.BackColor = Color.Red
End If
lblA1.Visible = False
lblA2.Visible = True
Application.DoEvents()
If boolEscape = True Then
MsgBox("You have STOPPED the measurment logging...", vbOKOnly)
boolEscape = False
Exit Sub
End If
ShowRXon()
txtRaw2.Text = mySerialPort.ReadLine
ShowRXoff()
txtBolt2.Text = txtRaw2.Text.Substring(7, 4)
If checkValue(txtBolt2.Text) = False Then
txtBolt2.BackColor = Color.Red
End If
lblA2.Visible = False
lblA3.Visible = True
Application.DoEvents()
If boolEscape = True Then
MsgBox("You have STOPPED the measurment logging...", vbOKOnly)
boolEscape = False
Exit Sub
End If

我该如何将其添加到一个单独的线程中,或者将datareceived事件识别为一种更好的方法,因为行总是相同的长度,并且总是以CRLF结尾。。。如果是的话,我修改它以使用它有多冷。

一般来说,您应该处理SerialPortDataReceived事件。您可以在ButtonClick事件中启动任何您喜欢的过程,但这只是启动。当SerialPort对象接收到数据,然后处理该数据时,将引发DataReceived事件。如果您希望六次接收一行数据,那么您可以在事件处理程序中调用ReadLine,该事件可能会引发六次。

不需要启动任何多线程,因为它已经为您完成了,即DataReceived事件在辅助线程上引发,因此您的事件处理程序在辅助线程中执行。这意味着您不能直接访问该事件处理程序中的任何控件,也不能访问从事件处理程序调用的任何方法。您需要封送对UI线程的调用,以便更新UI。下面是一个向SerialPort发送多个命令并显示响应的简单示例:

Private commands As Queue(Of String)
Private Sub SendNextCommand()
If commands.Any() Then
SerialPort1.WriteLine(commands.Dequeue())
End If
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
commands = New Queue(Of String)({"First", "Second", "Third"})
SendNextCommand()
End Sub
Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim response = SerialPort1.ReadLine()
'This event is raised on a secondary thread so we must marshal to the UI thread to update the UI.
TextBox1.BeginInvoke(Sub() TextBox1.AppendText(response & Environment.NewLine))
SendNextCommand()
End Sub

最新更新