Everything is all right at first, but after a period of time, will not be able to accept to the readings, but after an hour or two to restart the program is normal again, excuse me which encountered a similar situation, what is the problem (software or hardware), or special set some parameters to initialize serial port?
CodePudding user response:
The readings in the method DataReceived eventsCodePudding user response:
Suggest you open a multi-threaded:
Dim SerialComm=New Threading. Thread (New Threading. ThreadStart (AddressOf Sp_Receiving))
SerialComm. Start () 'open thread
Private Sub Sp_Receiving ()
Dim strIncoming As String
Try
If SerialPort1. BytesToRead & gt; 0 Then
StrIncoming=SerialPort1. ReadExisting. ToString 'data in a read buffer
SerialPort1. DiscardInBuffer ()
'strIncoming=SerialPort1. ReadLine. ToString
'SerialPort1. DiscardInBuffer ()
'ListBox1. Items. The Add (Microsoft) VisualBasic) Left (strIncoming, InStr (strIncoming vbCr) - 1))' to a carriage return position number - 1
'the ListBox1. Items. The Add (Mid (strIncoming, 1, Len (strIncoming) - 1))' length - 1
ListBox1. Items. The Add (strIncoming)
ListBox1. SelectedIndex=ListBox1. Items. The Count - 1
If ListBox1. Items. Count & gt; Then 1000
Me. The ListBox1. Items. The Clear ()
End the If
End the If
Catch the ex As Exception
MessageBox. Show (ex. Message)
End the Try
End Sub
CodePudding user response:
Not sure where is the position of the upper or lower machine, can get a mature software to simulate serial communication, your timing operation, to determine what the problem, then find the solution,CodePudding user response:
Just like luoPrivate WithEvents mPort As SerialPort
The Event RequestData ()
The Event Ready ()
The Event Interrupt ()
The Event RerequestData ()
Sub New (PortName As String, BaudRate As Integer)
MPort=New SerialPort (PortName BaudRate)
Try
MPort. The Open ()
Catch the ex As Exception
MsgBox (ex. ToString)
End the Try
End Sub
Private Sub mPort_DataReceived (sender As Object, e As SerialDataReceivedEventArgs) Handles mPort. Method DataReceived
Dim inData As String=CType (sender, SerialPort) ReadLine. TrimEnd ({CChar (vbCr), CChar (vbLf)})
If the inData=https://bbs.csdn.net/topics/(r_RequestData) Then
RaiseEvent RequestData ()
ElseIf inData=https://bbs.csdn.net/topics/(r_Ready) Then
RaiseEvent Ready ()
ElseIf inData=https://bbs.csdn.net/topics/(r_Interrupt) Then
RaiseEvent Interrupt ()
Then ElseIf inData=https://bbs.csdn.net/topics/r_RerequestData
RaiseEvent RerequestData ()
ElseIf inData & lt;> String. The Empty Then
The Debug. Print (" unknown request received lower machine, [" & amp; inData & amp; "] ")
End the If
End Sub
Private Sub mPort_Disposed (sender As Object, As EventArgs e) Handles mPort. Disposed
Try
If mPort IsNot Nothing AndAlso mPort. IsOpen Then
Clear ()
MPort. Close ()
End the If
Catch the ex As Exception
End the Try
End Sub
Protected Friend Sub the Clear ()
Try
MPort. BaseStream. Flush ()
Catch the ex As Exception
End the Try
End Sub