Serial Port Complete - Latest Microcontroller projects

(lily) #1
Using .NET’s SerialPort Class

The default is the constant SerialPort.InfiniteTimeout, which never times out.
Microsoft’s documentation says the values must be either greater than zero or
SerialPort.InfiniteTimeout. A timeout raises a TimeoutException.
The best values to use for timeouts depend on the bit rate and the size of the
largest transfers expected in each read or write operation. For example, at 300
bps and parameters of 8-N-1, a 1024-byte array requires over 34 seconds to
transmit. At 115,200 bps, the same array can transmit in under 0.1 second.
Delays due to flow control can slow a transfer further. Chapter 10 has more
about setting timeouts.

  8 
1 


A DataReceived event can inform an application that data is available for read-
ing in the receive buffer. The ReceivedBytesThreshold property determines how
many bytes must be present in the buffer before the event is raised. The default
is one byte. If you set the property to a larger number, the DataReceived event
is likely to be raised less often and each event will likely have more data to pro-
cess.
Setting a threshold greater than 1 can prevent the receiving computer from see-
ing some or all of the received data. For example, assume that Received-
BytesThreshold in the receiving computer is set to 4 and the transmitting
computer sends 3 bytes. The buffer holds fewer bytes than the threshold, so the
DataReceived event isn’t raised. Unless the transmitting computer sends
another byte or the receiving computer polls the receive buffer, the application
doesn’t know the bytes arrived.

  

 


An application that has finished communicating with a port should close the
port and free its resources to allow other applications to use the port if needed.
The Close method closes the connection to the port and clears the receive and
transmit buffers. The Dispose method calls the Close method and releases all
resources used by the component, making it possible to reopen a port quickly
after closing it.
Attempting to close a port that doesn’t exist causes a NullReferenceException.
Attempting to close a port that isn’t open causes an InvalidOperationException.
To avoid these exceptions, check to see that the port exists and is open before
closing it.
Free download pdf