Opening a Serial Port
Problem
You want to set up a serial port and open it for input/output.
Solution
Use a
CommPortIdentifier
’s open( )
method to get a SerialPort
object.
Discussion
Now you’ve picked your serial port, but it’s not ready to go yet. Baud rate. Parity. Stop bits. These things have been the bane of many a programmer’s life. Having needed to work out the details of setting them on many platforms over the years, including CP/M systems, IBM PCs, and IBM System/370 mainframes, I can report that it’s no fun. Finally, Java has provided a portable interface for setting all these parameters.
The steps in setting up and opening a serial port are as follows:
Get the name and
CommPortIdentifier
(which you can do using myPortChooser
class).Call the
CommPortIdentifier
’sopen( )
method; cast the resultingCommPort
object to aSerialPort
object (this cast will fail if the user chose a parallel port!).Set the serial communications parameters, such as baud rate, parity, stop bits, and the like, either individually or all at once using the convenience routing
setSerialPortParams( )
.Call the
getInputStream
andgetOutputStream
methods of theSerialPort
object, and construct any additionalStream
orWriter
objects (see Chapter 9).
You are then ready to read and write on the serial port. Example 11-2 is code that implements all these steps for a serial port. Some of this code is for parallel ports, which we’ll discuss in Section 11.4.
Example 11-2. CommPortOpen.java
import java.awt.*; import ...
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.