Serial Communication between Java RXTX and Arduino

SharpBarb picture SharpBarb · Jan 5, 2010 · Viewed 21.3k times · Source

I'm trying to communicate between my PC (Windows 7 using Netbeans and RXTX) with an Arduino Pro, using the serial port. The Arduino is actually connected to the PC using an FTDI cable.

The code is based on the Java SimpleRead.Java found here.

Currently the Arduino simply prints out a string when it starts up. My Java program should print the number of bytes that have been read and then print out the contents. The Java program works, sort of...

If the string is long (>10 bytes or so) the output will get broken up.

So if on the Arduino I print

Serial.println("123456789123456789"); //20 bytes including '\r' and '\n'

The output of my Java program may look something like:

Number of Bytes: 15   
1234567891234  
Number of Bytes: 5  
56789

or

Number of Bytes: 12   
1234567891  
Number of Bytes: 8  
23456789

I'm thinking it's a timing problem, because when I manually go through the code using the debugger, the result string is always what it should be: one 20 byte string.

I've been messing with various things but I haven't been able to fix the problem.

Here is the part of the code that is giving me problems:

static int baudrate = 9600,
           dataBits = SerialPort.DATABITS_8,
           stopBits = SerialPort.STOPBITS_1,
           parity   = SerialPort.PARITY_NONE;    

byte[] readBuffer = new byte[128];

...
...

public void serialEvent(SerialPortEvent event)
{
   if (event.getEventType() == SerialPortEvent.DATA_AVAILABLE) {

    try {
        if (input.available() > 0) { 
            //Read the InputStream and return the number of bytes read
            numBytes = input.read(readBuffer);

            String result  = new String(readBuffer,0,numBytes);
            System.out.println("Number of Bytes: " + numBytes);
            System.out.println(result);
        }
    } catch (IOException e) {
        System.out.println("Data Available Exception");
    }
}

Answer

R Samuel Klatchko picture R Samuel Klatchko · Jan 5, 2010

Serial data is just a stream of data. Depending on when you read it and the buffering that is happening, only part of the data may be available when you read it.

Since you are using line oriented data, what you will want to do is buffer the data until you see the line terminator and only then process the data.