我有一个距离跟踪激光连接到我的 COM1 端口,我正在使用这些设置来初始化连接:
With ServoCalibrater.LaserPort
.BaudRate = 19200
.DataBits = 8
.StopBits = IO.Ports.StopBits.One
.Parity = IO.Ports.Parity.None
.StopBits = IO.Ports.StopBits.One
.Close()
.Open()
.Write("dt")
End With
然后我用这个函数处理接收到的数据:(Reading 是 double 类型的全局变量,ErrorMessage 是 string 类型的全局变量)
Private Sub LaserPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles LaserPort.DataReceived
ComRecv = True
Dim TempRead As String
TempRead = LaserPort.ReadExisting()
If Not IsNumeric(TempRead) Then
If Asc(TempRead) = 13 Then
TempRead = "*No Data*"
End If
ErrorMessage = "Laser Error " & TempRead & "... Please restart application, then turn laser off and back on."
Else
Reading = ErrorMessage
End If
End Sub
从这里我想把Reading
值放到我的表单上。我不能直接在方法中这样做,因为它不是线程安全的。所以我目前尝试的解决方案是让计时器检查Reading
每十分之一秒的值并添加到表单中。我在这个刻度方法中这样做:
Private Sub tmrMonitor_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrMonitor.Tick
Dim MeasuredDistance As New clsDimension
Dim DesiredDistance As New clsDimension
'Check to see if we've got com with the laser so we can alert the user if not
If Not ServoCalibrater.ComRecv Then
LaserError.Text = "No communication received from the laser. Please check to make sure it's turned on."
Else
CurrentPosText.Text = Reading
Refresh()
End If
End Sub
使用调试器单步执行时,上面的代码似乎运行良好。但是,当在没有调试器的情况下显示 Form 时,CurrentPosText.Text 中显示的数字与激光的预期值完全不同。
我通过Putty.exe发出相同的命令来检查以确保激光值正确。
以下是 Putty 的一致结果和设置。(点击链接并观看视频)
TLDR观看此视频!
在没有调试器的情况下显示在表单上时,我从 COM 端口收到的数字如何以及为什么会发生变化?