Class to access serial ports
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);
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
!
To see more, please:
- Consult
XSerialPort
JAVADOC; - See our samples!