public void write(final String pMessageString) { System.out.println("\n>>> \"" + pMessageString + "\" to " + serialPort.getName()); try { out.write(pMessageString.getBytes()); } catch (IOException e) { e.printStackTrace(); } }
public void connect() { _serialPort.setBaud(115200); _serialPort.setParity(gnu.io.SerialPort.PARITY_NONE); _serialPort.setDataBits(gnu.io.SerialPort.DATABITS_8); _serialPort.setStopBits(gnu.io.SerialPort.STOPBITS_1); _serialPort.setFlowControl(gnu.io.SerialPort.FLOWCONTROL_NONE); _serialPort.open(); try { for (int n = 0; n < 20; n++) { _serialPort.writeLn("99"); // writeLn flushes automatically Thread.sleep(250); if (_serialPort.available() > 0) { String response = _serialPort.readLine(); if (response.equals("11")) { Thread.sleep(250); while (_serialPort.available() > 0) _serialPort.readChar(); _isConnected = true; return; } _serialPort.close(); throw new RuntimeException( "Arduino.connect: Arduino board present but running incorrect firmware on port " + _serialPort.getName()); } Thread.sleep(250); } } catch (InterruptedException e) { throw new RuntimeException( "Arduino.connect: interrupted while waiting for response from Arduino on port" + _serialPort.getName()); } _serialPort.close(); throw new RuntimeException( "Arduino.connect: Arduino board present but running incorrect firmware on port " + _serialPort.getName()); }
// disconnect the serial port // pre: an open serial port // post: clsoed serial port public void disconnect() { // close the serial port try { // writeData(0, 0); serialPort.removeEventListener(); serialPort.close(); input.close(); output.close(); setConnected(false); logText = "Disconnected."; System.out.println(logText + "\n"); } catch (Exception e) { logText = "Failed to close " + serialPort.getName() + "(" + e.toString() + ")"; System.out.println(logText + "\n"); } }