问题描述
我正在为工作中的测试设备编写 Arduino 数据记录/处理程序并在 VB.net 中编码,因为我在该语言方面有几年的经验,并认为这比重新学习 C# 更快。 我目前遇到的问题有时是在调试 Serialport.Datarecieved 事件期间不会触发并且不会触发,直到我删除事件处理程序代码块并重新创建它。 这样做时,我复制 sub 的内容,删除块并重新创建它,然后将代码粘贴回块中,然后我又得到了。 我尝试在程序开始时通过 addhandler 调用处理程序,以在 form1.load 上以编程方式设置它,但这没有帮助。
Imports System
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports
Public Class Form1
Public WithEvents com1 As New IO.Ports.SerialPort
'serial port recreated and connection details set.
com1 = New IO.Ports.SerialPort(cb_Comms.Text,cb_Baud.Text,Parity.None,8,StopBits.One)
com1.Handshake = Handshake.None
com1.WriteTimeout = 10
com1.ReadTimeout = 10
Private Sub com1_DataReceived() (sender As Object,e As SerialDataReceivedEventArgs)
Me.BeginInvoke(Sub() PortRead())
End Sub
任何帮助将不胜感激。谢谢
解决方法
Messages recieved from arduino finish in vbcrlf
私有函数 PortRead() As String
Dim msg As String = ""
If Not IsNothing(com1) AndAlso com1.IsOpen Then
tick = True
'string format Capacity tester *C5;V3.22;C102.30;E
'string format 150A tester *!5;V3.22;C102.30;E
Dim MsgIn As String = ""
Try
Try
MsgIn = com1.ReadTo(vbcrlf)
Catch ex As Exception
'Stop
End Try
If MsgIn.Length >= 0 Then
MsgIn = MsgIn.Replace(vbCrLf,"").Trim()
If cb_Date.Checked Then rtb_Serial.Text += DateTime.Now.ToString()
rtb_Serial.Text = MsgIn + vbCrLf + rtb_Serial.Text
If MsgIn.StartsWith("*C") Or MsgIn.StartsWith("*!") Then
Try
Process_Data(MsgIn)
Catch ex As Exception
MessageBox.Show("Message Processing Fail" + vbCrLf + MsgIn,"A15")
End Try
End If
Return MsgIn
Else
Return ""
End If
Catch e As Exception
If Not e.Message = "The operation has timed out." Then
MessageBox.Show("Error Reading Port: " + com1.PortName + vbCrLf + e.Message + vbCrLf + "Port " + com1.PortName + " Closed","A13")
com1.Close()
End If
End Try
End If
rtb_Serial.Update()
Return msg
End Function