Java Serial

This is how I read serial with Java.

Reading the serial port onto the computer can sometimes be tricky, this is mostly due to the read buffer of the serial port. On a microcontroller it’s one byte at a time, so you can easily process the data if you know what to expect.

With a buffer that can hold more than one byte, you get all your bytes but they may be together in an array or individual. Sometimes you want to process bytes individually so this can make it tricky.

I tried with Visual Studio C# and this tends to happen.  But with Java I have had more success.
The program here is a simple program that prints out bytes of data as they come in. It still has a buffer and can still put the data together in an array.. But what I’ve found here is, bytes sent individually are individual bits on the array, but bytes sent together (like a MIDI data stream for example) are placed in the array.

So it is easier to program with what data is expected.

Download

Click Here to download.
The program is a netbeans project, so can be directly opened in netbeans.

To run in a command line

The dist folder has the JAR file and the serial comm in the lib folder.
Go to this directory and run

java -jar JavaSerialDisplay.jar

The same command works on all platforms (you need Java on your computer of course!)

The program

The program uses the library jSerialComm.
https://fazecast.github.io/jSerialComm/

When this program is run, it lists all ports with an index number. You need this to set what port to use.
The program will exit if no ports are found.

Command Line

You can send a command line argument with the array number, if no argument is sent it opens the first port (0) with a baud of 9600. This can be changed at the top of the program.

Each block of the program is divided up with a //***** BLOCK 1 etc comment.

Block:
1 – Lists the serial ports on the system
2 – Reads the command argument and changes the port
3 – Sets the event listener to read the port

So you can remove BLOCK 1 and BLOCK 2 if you don’t need those functions.

 

The received data
There is a for loop on BLOCK 4 that reads the bytes. Even if the bytes have come in together, this loop can be used to process them individually, if only one byte comes in, the loop runs once.

Below is the example of the data reading on block 4

for (int i = 0; i < newData.length; ++i) {
System.out.print(i + ” : “);
System.out.println(newData[i]);
}

The first print is just the array location, the second is the data in the array newData

Read serial with Java and process your data!