// class variables used for communication: private String readline = ""; private String comPort = "COM5"; // change this port to the current one from the Arduino IDE private SerialPort port; /** * Connect to COM-port specified in class-variable comPort. * Setup an eventlistener to respond to data send from Arduino. * Based on: * jSerialComm Event-Based Reading Usage Example * https://github.com/Fazecast/jSerialComm/wiki/Event-Based-Reading-Usage-Example */ public void connect() { /* // get a list of available ports: SerialPort ports[] = SerialPort.getCommPorts(); for (int i = 0; i < ports.length; ++i) { System.out.println(ports[i].getDescriptivePortName()); } // comPort = SerialPort.getCommPorts()[0]; */ System.out.println("Connecting to "+comPort+" ..."); port = SerialPort.getCommPort(comPort); port.openPort(); port.addDataListener(new SerialPortDataListener() { @Override public int getListeningEvents() { return SerialPort.LISTENING_EVENT_DATA_AVAILABLE; } @Override public void serialEvent(SerialPortEvent event) { if (event.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE) return; byte[] newData = new byte[port.bytesAvailable()]; int numRead = port.readBytes(newData, newData.length); // System.out.println("Read " + numRead + " bytes."); if (numRead > 0) { for (int i = 0; i < newData.length; ++i) { if ((char)newData[i]=='\n'||(char)newData[i]=='\r') { readline=readline.trim(); if (readline.length()>0) receive(readline); readline=""; } else readline=readline+(char)newData[i]; } } } }); } // end of method connect() /** * If a line of text is received, process it * @param line */ private void receive(String line) { System.out.println(line); } // end of method receive() /** * Send a message m to the connected COM-port * @param m */ public void send(String m) { port.writeBytes(m.getBytes(), m.length()); } // end of method send()