16,722
社区成员




Private WithEvents mPort As SerialPort
Event RequestData()
Event Ready()
Event Interrupt()
Event RerequestData()
Sub New(PortName As String, BaudRate As Integer)
mPort = New SerialPort(PortName, BaudRate)
Try
mPort.Open()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub mPort_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles mPort.DataReceived
Dim inData As String = CType(sender, SerialPort).ReadLine.TrimEnd({CChar(vbCr), CChar(vbLf)})
If inData = (r_RequestData) Then
RaiseEvent RequestData()
ElseIf inData = (r_Ready) Then
RaiseEvent Ready()
ElseIf inData = (r_Interrupt) Then
RaiseEvent Interrupt()
ElseIf inData = r_RerequestData Then
RaiseEvent RerequestData()
ElseIf inData <> String.Empty Then
Debug.Print("收到下位机的未知请求。[" & inData & "]")
End If
End Sub
Private Sub mPort_Disposed(sender As Object, e As EventArgs) Handles mPort.Disposed
Try
If mPort IsNot Nothing AndAlso mPort.IsOpen Then
Clear()
mPort.Close()
End If
Catch ex As Exception
End Try
End Sub
Protected Friend Sub Clear()
Try
mPort.BaseStream.Flush()
Catch ex As Exception
End Try
End Sub
Dim SerialComm = New Threading.Thread(New Threading.ThreadStart(AddressOf Sp_Receiving))
SerialComm.Start() '开线程
Private Sub Sp_Receiving()
Dim strIncoming As String
Try
If SerialPort1.BytesToRead > 0 Then
strIncoming = SerialPort1.ReadExisting.ToString '读取缓冲区中的数据
SerialPort1.DiscardInBuffer()
'strIncoming = SerialPort1.ReadLine.ToString
'SerialPort1.DiscardInBuffer()
'ListBox1.Items.Add(Microsoft.VisualBasic.Left(strIncoming, InStr(strIncoming, vbCr) - 1)) '取到回车符位置数-1
'ListBox1.Items.Add(Mid(strIncoming, 1, Len(strIncoming) - 1)) '长度-1
ListBox1.Items.Add(strIncoming)
ListBox1.SelectedIndex = ListBox1.Items.Count - 1
If ListBox1.Items.Count > 1000 Then
Me.ListBox1.Items.Clear()
End If
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub