It is rare to get a timeout when writing.  I usually get this when I
am reading a port.  What value did you use for the timeout when you
configured the port?  I think the default is 10,000 ms, i.e. 10
seconds.  If it were timing out, you would notice the code hanging for
10 seconds as the serial I/O function tries to run to completion.

To avoid timeouts, check the following in your code.

1) Make sure the configured timeout is long enough to handle the data
stream sent on your write.  If you are sending a long stream of data,
you should test the time it takes and make sure the timeout is larger
than the longest time for your longest data stream.

2) When you are reading a port, make sure the number of bytes you
request is equal to or smaller than the number of bytes being sent
from your serial device hanging on the other end of the cable.
Otherwise, it will always use the entire alotted time (the timeout
value) attempting to read the data.

3) Verify that the response time of your device is not abnormally
slow.  Some devices don't interrupt processes very quickly.  In fact,
some devices put a very low priority on the serial port and may not
respond at all while executing certain functions.  You need to set the
timeout value to be long enough to account for the device's response
time when reading a response from your device.

If you don't know what to use as a timeout value, always start with a
long one and try to handle timing variations in your code, e.g. read
or write the data in chunks perform sanity checks as you go.  Long
delays in the response of your code will point you to a bug in the
handling of serial port communications.  You will get a long delay
everytime the serial command cannot complete due to an unreasonable
request, e.g. telling it to read 100 bytes when the device can only
return 16 bytes for the requested command.

You can use the NumberOfBytesAtPort property to help you determine
when data is available for reading.  Also, in a loop that may be used
to poll a serial port, try to use a wait (the wristwatch timing
function).  This keeps you from pummeling the serial port to hard with
futile requests.

Another good way to avoid serial timeouts is to use a termination
character.  If your device always expects a <cr> as the last character
in a command, or if it always sends a <cr> as the last character in a
response, then configure your port to terminate a transmission
automatically upon receiving the <cr> character.  I think the default
termination character is <lf> (linefeed character) it you elect to
enable this feature in your configuration.

Reply via email to