Page 41 - The Definitive Guide to Building Java Robots
P. 41
Preston_5564C02.fm Page 22 Wednesday, September 14, 2005 5:42 AM
22 CHAPTER 2 ■ SERIAL COMMUNICATION
■Note The two pause methods are there to wait for the driver to set the values of the ports. I have found
on my Windows XP machine that if I don’t pause a little, the drivers sometimes return exceptions. You can
remove these on your machine if you wish, just be sure to stress test them by trying many port open and
closes in a loop.
Next, I’ll discuss the implementation classes of the JSerialPort interface. (See Example 2-4.)
The read() method is really just a method that sleeps until the input buffer is empty. Once
empty, it returns the contents of the readBuffer. The readString() method just calls the read()
method and then converts the bytes into a tilde-delimited list as a String. Since all the data
coming from the microcontroller will be a stream of bytes, I wanted a way to read individual
bytes without having to worry about them being changed into a character that could not be
easily converted back to an int.
The write() method is a pass-through to the output stream with the exception of adding
the contents to the currentWrite byte[]. I keep this because I want to ignore it if the microcontroller
echoes it back to me while reading the input stream.
The close() method closes the SerialPort.
The two other methods—read() and readString() with input parameters—are not used but
are once again there because the jSerialPort interface requires them.
The only event I care about is the DATA_AVAILABLE event. When this event is triggered,
I’ll initialize a 32-byte array, and then while the inputStream is available, I’ll read the input
stream into the readBuffer. I then perform some logic to make sure that the data returned is not
equal to the data sent, and if that’s the case, I set the dataIn Boolean to true.
Of the last three methods, setTimeout() is not used, and setDTR() and getName() are there
to provide limited access to their corresponding SerialPort variables.
An example sequence of events for a typical write/pause/read action would be the following:
1. byte[] is written to a serial port.
2. The microcontroller reads byte[].
3. The external program calls pause(x).
4. Time passes.
5. Time is up.
6. The microcontroller returns byte[].
7. The standard serial port event DATA_AVAILABLE is triggered.
8. The external program calls read().
9. All data is read; dataIn is set to true.
10. The read returns byte[] of data from microcontroller.