Skip to content

Nonblocking Reading Usage Example

Will Hedgecock edited this page Mar 12, 2015 · 3 revisions

Non-blocking reading is the default mode used by this library. It can be selected simply by opening the COM port with no other options:

SerialPort comPort = SerialPort.getCommPorts()[0];
try {
   while (true)
      while (comPort.bytesAvailable() == 0)

      byte[] readBuffer = new byte[comPort.bytesAvailable()];
      int numRead = comPort.readBytes(readBuffer, readBuffer.length);
      System.out.println("Read " + numRead + " bytes.");
} catch (Exception e) { e.printStackTrace(); }

If you were already in a different mode of operation, you can enable non-blocking/polling mode by calling the following method at any point in time:

comPort.setComPortTimeouts(SerialPort.TIMEOUT_NONBLOCKING, 0, 0);