Serial ports occasionally timeout during write command (The thread 0x416c has exited with code 0 (0x0).) and throws an exception.

  • Thread starter Thread starter m_frantz1
  • Start date Start date
M

m_frantz1

Guest
I am trying to write bytes out to a serial port.

I have tried this code on multiple PCs, multiple serial ports. My current test is just to write the data out to a serial port and wait. Repeat as necessary. It still fails multiple times per 1000 attempts.

I have tried all types of .writetimeout (-1, 500, 1000, 2000, 3000 + )

I added a delay of 50 ~ 250 milliseconds to ensure that I was not rolling over the serial port.

I have tried writing strings, bytes, byte arrays

As a compiled version, this failure locks the program up and crashes.

Here is my source code: ( I boiled it down to write was failing and just tested this function in high speed...)

----------------------------------------------------



Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'Serial port settings (SECS GEM)
SerialPortA.BaudRate = 4800
SerialPortA.DataBits = 8
SerialPortA.Parity = 0 'cbo_Parity.SelectedIndex
SerialPortA.StopBits = 1
SerialPortA.ReadBufferSize = 6000
SerialPortA.PortName = "COM8" 'cbo_SerialPortANumber.SelectedItem
'SerialPortA.WriteTimeout = 2000

SerialPortA.Open()
SerialPortA.DiscardInBuffer()
SerialPortA.DiscardOutBuffer()



i = 0
While True
' On Error Resume Next



If SerialPortA.IsOpen = True Then
Delay(50)
While SerialPortA.CtsHolding = True
Debug.Print("?")
End While
If SerialPortA.BytesToWrite > 0 Then
Debug.Print("Non empty buffer")
End If

SerialPortA.Write("A")
i += 1

If (i Mod 100) = 0 Then

Debug.Print(i)
End If


If i > 10000 Then
Debug.Print("Done")

End If

End If

End While

end sub

Private Sub Delay(DelayTime As Integer)
Dim DelayStartTime As DateTime

DelayStartTime = Now()
elapsedtime = Now().Subtract(DelayStartTime)


While elapsedtime.TotalMilliseconds < DelayTime
elapsedtime = Now().Subtract(DelayStartTime)
End While

End Sub

----------------------------------------------------

Here are the number of times it failed (only show every 100 sends...) but I can get it to fail more frequently in my regular program.

100
200
300
400
500
The thread 0x2d80 has exited with code 0 (0x0).
600
700
800
The thread 0xd1c has exited with code 0 (0x0).
900
1000
1100
The thread 0x57d4 has exited with code 0 (0x0).
1200

Continue reading...
 
Back
Top