0% found this document useful (0 votes)
28 views

Prog Java

This document demonstrates how to use the jSerialComm library to open a serial port, write a test message to the port, read data from the port into a buffer, and close the port. It gets a list of available serial ports, opens the last port in the list, sets the read timeout to non-blocking, writes and reads a test message as bytes, and prints the results.

Uploaded by

even holz
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

Prog Java

This document demonstrates how to use the jSerialComm library to open a serial port, write a test message to the port, read data from the port into a buffer, and close the port. It gets a list of available serial ports, opens the last port in the list, sets the read timeout to non-blocking, writes and reads a test message as bytes, and prints the results.

Uploaded by

even holz
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

byte[] readBuffer = new byte[2048];

byte[] outputMessage = "Test Message to Transmit".getBytes(StandardCharsets.UTF_8);

System.out.println("\nUsing jSerialComm Library Version v" + SerialPort.getVersion());

SerialPort[] ports = SerialPort.getCommPorts();

System.out.println("\nAvailable Ports:\n");

for (int i = 0; i < ports.length; ++i)

System.out.println(" [" + (i+1) + "] " + ports[i].getSystemPortName() + ": " +


ports[i].getDescriptivePortName() + " - " + ports[i].getPortDescription());

if (ports.length == 0) {

System.out.println(" No Ports Detected!");

return;

SerialPort serialPort = ports[ports.length - 1];

boolean openedSuccessfully = serialPort.openPort();

System.out.println("\nOpening " + serialPort.getSystemPortName() + ": " +


serialPort.getDescriptivePortName() + " - " + serialPort.getPortDescription() + ": " + openedSuccessfully);

if (!openedSuccessfully)

return;

System.out.println("Setting read timeout mode to blocking with no timeout");

serialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING, 0, 0);

System.out.println("\nWriting message to serial port: \"" + new String(outputMessage,


StandardCharsets.UTF_8) + "\"");

serialPort.writeBytes(outputMessage, outputMessage.length);

System.out.println("Writing complete!\nReading message from serial port ");


System.out.flush();

int numBytesRead = serialPort.readBytes(readBuffer, readBuffer.length);

System.out.println("(" + numBytesRead + " bytes read): \"" + new String(readBuffer,


StandardCharsets.UTF_8) + "\"");

System.out.println("Reading complete!\n");

System.out.println("Closing " + serialPort.getDescriptivePortName() + ": " +


serialPort.closePort());

You might also like