Saturday, August 2, 2014

Using Java RxTx library for Serial Communication With Arduino - Part 2

Hi All,

In the previous post I showed you how you can use the Java RxTx library to find the Arduino connected COM port. Now let's do something useful. We can use this for reading values sent from the Arduino. With the values, we can play around and do whatever we like. In this post I'm using the code provided by Arduino.

First let's write a tiny Arduino program that prints some strings to Serial.

void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.print("STX,");
Serial.print("Test Serial Communication Line,");
Serial.println("ETX");
}
view raw gistfile1.txt hosted with ❤ by GitHub


Then lets use the code provided by Arduino for reading values from Arduino. So here it is. I have just modified the code to split the chunks from the input string. (Line 81)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;
public class SerialTest implements SerialPortEventListener {
SerialPort serialPort;
/** The port we're normally going to use. */
private static final String PORT_NAMES[] = {"/dev/tty.usbserial-A9007UX1", // Mac OS X
"/dev/ttyUSB0", // Linux
"COM7", // Windows
};
private BufferedReader input;
private OutputStream output;
private static final int TIME_OUT = 2000;
private static final int DATA_RATE = 9600;
public void initialize() {
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
//First, Find an instance of serial port as set in PORT_NAMES.
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
System.out.println("Could not find COM port.");
return;
}
try {
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
// open the streams
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
} catch (Exception e) {
System.err.println(e.toString());
}
}
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
public synchronized void serialEvent(SerialPortEvent oEvent) {
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
String inputLine=null;
if (input.ready()) {
inputLine = input.readLine();
String [] chunks = inputLine.split(",");
System.out.println(inputLine);
System.out.println(chunks[0] + "\t" + chunks[1] + "\t" + chunks[2] + "\t");
}
} catch (Exception e) {
System.err.println(e.toString());
}
}
// Ignore all the other eventTypes, but you should consider the other ones.
}
public static void main(String[] args) throws Exception {
SerialTest main = new SerialTest();
main.initialize();
Thread t=new Thread() {
public void run() {
//the following line will keep this app alive for 1000 seconds,
//waiting for events to occur and responding to them (printing incoming messages to console).
try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
}
};
t.start();
System.out.println("Started");
}
}
view raw gistfile1.txt hosted with ❤ by GitHub


So that it.

Hope it would help.

Thank you. :-)




5 comments:

  1. So? Finish? Only this two tutorial :(

    ReplyDelete
    Replies
    1. Hi Paolo, sorry to disappoint you. :-) But you could also try my next blog post on showing arduino data in JFreeChart. Will try to do some more.

      Delete
  2. What about writing data to the arduino? I have tried using the output stream from the serial port to write data but my arduino seems to never receive it. I have assumed it has something to do with the baud rate on my computer vs my arduino, but I am unsure of this.

    ReplyDelete
  3. So The RxTx library can communication with other microprocessor?

    ReplyDelete
  4. hi
    i test this example but i have this error
    "Failed to write core dump. Minidumps are not enabled by default on client versions of Windows"

    ReplyDelete