Page 38 - The Definitive Guide to Building Java Robots
P. 38
Preston_5564C02.fm Page 19 Wednesday, September 14, 2005 5:42 AM
CHAPTER 2 ■ SERIAL COMMUNICATION 19
For later classes, it will be useful to not use the Thread.sleep() method, but to instead add
a single static method that you can call, and which handles the InterruptedException. For this,
I am going to create a Utils class to store these static utility methods. (See Example 2-2.)
Example 2-2. The Utils.pause() method
public static void pause(long ms) {
try {
Thread.sleep(ms);
} catch (Exception e) {
e.printStackTrace();
}
}
Section Summary
All communications used throughout this book with your microcontroller will employ RS-232
serial communication at 9600 baud, eight data bits, one stop bit, and no flow control. Once this
is configured on your PC using a combination of the classes CommPortIdentifier and SerialPort
from Java Communications API for serial communication, you should be able to get access that
let’s you both read and write to and from your PC’s serial port with Java.
The classes I created in this section were
• ListOpenPorts.java: This class showed how to iterate through the enumeration provided
by the Java API CommPortIdentifier class to select a serial port.
• Utils.pause(): This class is going to be just a utility class that currently has a pause
method which will cause the current thread to sleep and trap its exception.
While you can use the API directly, I’ve found it more helpful to write a wrapper class that
simplifies access. This is what I will talk about in the next section.
2.1 A Simple Serial Port
In the ListOpenPorts class, we were able to access and open the serial ports, but using this tech-
nique presents three problems. First, it’s cumbersome to create and use the serial port by
iterating through all those that are available, and then when the one that’s available matches
the one you want, you can use it. Second, using the input streams and output streams from the
serial port is difficult if you want to send and receive data packets as defined in Chapter 1.
Third, the usage of this port is not generic enough.
Code Objectives
To compensate for these shortcomings I am going to create the following:
• A serial port interface so that I can create multiple serial port implantation classes, but
won’t have to modify the code using the interface.
• A simpler constructor so that I can specify a serial port with baud and identifier.