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 myPortChooserclass).Call the
CommPortIdentifier’sopen( )method; cast the resultingCommPortobject to aSerialPortobject (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
getInputStreamandgetOutputStreammethods of theSerialPortobject, and construct any additionalStreamorWriterobjects (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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access