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:

  1. Get the name and CommPortIdentifier (which you can do using my PortChooser class).

  2. Call the CommPortIdentifier’s open( ) method; cast the resulting CommPort object to a SerialPort object (this cast will fail if the user chose a parallel port!).

  3. 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( ).

  4. Call the getInputStream and getOutputStream methods of the SerialPort object, and construct any additional Stream or Writer 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.