O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Serial Ports

The javax.comm.SerialPort class is an abstract subclass of CommPort that provides various methods and constants useful for working with RS-232 serial ports and devices. The main purposes of the class are to allow the programmer to inspect, adjust, and monitor changes in the settings of the serial port. Simple input and output is accomplished with the methods of the superclass, CommPort. SerialPort has a public constructor, but that shouldn’t be used by applications. Instead, you should call the open() method of a CommPortIdentifier that maps to the port you want to communicate with, then cast the result to SerialPort. For example:

CommPortIdentifier cpi = CommPortIdentifier.getPortIdentifier("COM2");
  if (cpi.getType() == CommPortIdentifier.PORT_SERIAL) {
    try {
      SerialPort modem = (SerialPort) cpi.open();
    }
    catch (PortInUseException e) {}
  }

Methods in the SerialPort class fall into roughly three categories:

  • Methods that return the state of the port

  • Methods that set the state of the port

  • Methods that listen for the changes in the state of the port

Control Functions

Data cannot simply be sent over a wire; you need to deal with many issues, like timing, noise, and the fundamentally analog nature of electronics. Therefore, there’s a host of layered protocols so that the receiving end can recognize when data is being sent, whether the data was received correctly, and more.

Serial communication uses some very basic, simple protocols. Sending between 3 and 25 volts across the serial ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required