import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Enumeration; import java.util.TooManyListenersException; import gnu.io.CommPortIdentifier; import gnu.io.SerialPort; import gnu.io.SerialPortEvent; import gnu.io.SerialPortEventListener; import gnu.io.UnsupportedCommOperationException; public class SerialWork implements SerialPortEventListener{ /** * @param args */ public static void main(String[] args) { listPorts(); // example Arduino connection // new SerialWork("/dev/cu.usbserial-A2002nGt", 9600); // example SunSPOT connection new SerialWork("/dev/cu.usbmodem0000103D1", 9600); } SerialPort mySerialPort; InputStream in; OutputStream out; public SerialWork(String whichPort, int whichSpeed) { //which port you want to use and the baud come in as parameters try { //find the port CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(whichPort); //open the port mySerialPort = (SerialPort)portId.open("my_java_serial" + whichPort, 2000); //configure the port try { mySerialPort.setSerialPortParams(whichSpeed, mySerialPort.DATABITS_8, mySerialPort.STOPBITS_1, mySerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e){System.out.println("Probably an unsupported Speed");} //establish streams for reading and writing to the port try { in = mySerialPort.getInputStream(); out = mySerialPort.getOutputStream(); } catch (IOException e) { System.out.println("couldn't get streams");} // we could read from "in" in a separate thread, but the API gives us events try { mySerialPort.addEventListener(this); mySerialPort.notifyOnDataAvailable(true); } catch (TooManyListenersException e) {System.out.println("couldn't add listener");} } catch (Exception e) { System.out.println("Port in Use: "+e);} } byte[] buffer= new byte[1024]; public void serialEvent(SerialPortEvent event) { if (event.getEventType()== SerialPortEvent.DATA_AVAILABLE) { try { // we could use in.available() to see whether we have enough data //System.out.println(Integer.toBinaryString(in.read())); int length= in.available(); length= length<1024?length: 1024; in.read(buffer, 0, length); System.out.write(buffer, 0, length); } catch (IOException e) {} } } public static void listPorts(){ Enumeration portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { CommPortIdentifier portId = (CommPortIdentifier)portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL){ System.out.println(portId.getName() + " " +portId.getCurrentOwner()); } } } }