Skip to content

Instantly share code, notes, and snippets.

@acmlira
Last active September 1, 2020 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acmlira/6a96d4245ce1856f68b78ff29e4b8e0b to your computer and use it in GitHub Desktop.
Save acmlira/6a96d4245ce1856f68b78ff29e4b8e0b to your computer and use it in GitHub Desktop.
XSerialPort spotlight

XSerialPort spotlight

Class to access serial ports

Port setup

You can use setPortName() method to assign the desired serial device.

XSerialPort serialPort = new XSerialPort();

serialPort.setPortName("/tty/usb0");

After port setup, you can open it in read-only (r/o), write-only (w/o), or read-write (r/w) mode with open() method. Use close() method to close port and cancel I/O operations any time.

Warning: The serial port is always opened with exclusive access, pay attention to concurrent thread access.

serialPort.open(OpenMode.ReadWrite);

If you had a successful open port, XSerialPort will be configured with defaults values. You can reconfigure the to desired settings with setBaudRate(), setDataBits(), setParity(), setStopBits(), and setFlowControl() methods.

XSerialPort serialPort = new XSerialPort("/tty/usb0");

serialPort.setBaudRate(115200);
serialPort.setParity(Parity.EVEN);

Usage

You can use the read() or write() methods to do I / O operations. Alternatively the readLine() convenience method can also be invoked. If not all the data is read at once, the remaining data will need to be requested to the channel. XSerialPort's doesn't have a internal read buffer.

See the following example:

int numRead = 0, numReadTotal = 0;
byte[] buffer = new byte[64];

XSerialPort serialPort = new XSerialPort("/tty/usb0");

serialPort.setBaudRate(115200);

while (true) {
    // Place what was read in position 0 to 64 of the buffer
    numRead  = serialPort.read(buffer, 0, buffer.length);
    
    // Check for EOF
    if (numRead == -1)
      break;
    
    // Do something with the array here 
    
    numReadTotal += numRead;
}

read() is a non-blocking method so your aproach, blocking or non-blocking, depends only on how you handle events/polling. Use your algorithm with any UpdateListener or Thread!

See more

To see more, please:

  • Consult XSerialPort JAVADOC;
  • See our samples!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment