Hi all,
I am trying to capture and analyze my arduino's output in java. Seeing as I am running windows, I have decided to use the RXTX library to access the serial port in Java. I am very close to successfully receiving data, however I am having a small problem.
Here is my code:
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
public class SerialTest {
// Set up and connect to the serial port
public void connect(String portName) throws Exception {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if(portIdentifier.isCurrentlyOwned()) {
System.out.println("Error: Port is currently in use");
}
else {
CommPort commPort = portIdentifier.open(this.getClass().getName(), 2000);
if(commPort instanceof SerialPort)
{
SerialPort serialPort = (SerialPort)commPort;
serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
(new Thread(new SerialReader(in))).start(); // begin reading the serial port
}
else
System.out.println("Error: Only serial ports are handled.");
}
}
// facilitates the reading of the serial port
public static class SerialReader implements Runnable {
public SerialReader(InputStream in)
{
this.in = in;
}
public void run() {
byte[] buffer = new byte[1024];
int len = -1;
try
{
while( (len = this.in.read(buffer)) > -1 ) {
System.out.println( (new String(buffer, 0, len)) ); // convert the byte data to a string
}
} catch(IOException e) {
e.printStackTrace();
}
}
private InputStream in;
}
public static void main(String [] args) {
SerialTest tst = new SerialTest();
try
{
tst.connect("COM3");
} catch(Exception e) {
e.printStackTrace();
}
}
}
Here is the resulting output:
533
531
532
5
32
532
531
5
33
532
533
5
33
532
533
5
3
2
533
533
5
3
2
532
532
53
2
533
533
53
3
533
532
53
4
532
533
532
532
531
532
532
532
531
533
533
532
533
532
533
532
532
533
5
32
532
533
5
32
532
532
5
34
530
533
5
3
3
532
533
5
3
2
532
531
53
2
533
532
53
2
534
532
53
3
533
532
533
532
533
531
532
532
531
532
532
534
532
534
531
533
533
533
5
33
532
533
5
32
532
532
5
32
532
534
5
3
2
533
533
5
3
2
533
532
53
3
532
533
53
3
532
531
53
3
533
532
533
531
533
532
533
533
532
532
532
531
532
533
531
533
532
533
5
32
532
533
5
32
532
532
5
33
532
532
5
3
3
532
532
5
3
3
533
532
53
2
532
532
53
3
533
533
53
Where as the actual output (according to hyperterminal) should be something similar to:
533
532
533
533
532
533
531
...
Does anyone have any idea why the byte buffer is being converted so incorrectly? Also, is there a way to have the arduino write integers to the serial port as opposed to ASCII strings? Any help on this is greatly appreciated!