Serial Port Complete - Latest Microcontroller projects

(lily) #1

Chapter 9


When a port is transmitting, closing the port or clearing the transmit buffer can
crash Windows. To prevent crashes, wait for all data to transmit before closing
the port. To prevent an endless wait, set the port’s WriteTimeout property. On a
timeout, the port’s BytesToWrite property is set to zero, and the port can close
without a crash.

 If (Not (myComPort Is Nothing)) Then


‘ The COM port exists.

If myComPort.IsOpen Then

' Wait for the transmit buffer to empty.

Do While (myComPort.BytesToWrite > 0)
Loop

‘ The COM port is open; close it and dispose of its resourced.

myComPort.Dispose()
End If
End If

 if (!(myComPort == null))
{
// The COM port exists.


if ( myComPort.IsOpen )
{
// Wait for the transmit buffer to empty.

while (myComPort.BytesToWrite > 0)
{
}
// The COM port is open; close it and dispose of its resources.

myComPort.Dispose();
}
}
Free download pdf