private static String _guessWindowsPortName(ArrayList<String> portNames) { /* // if the for loop below this comment block does not work right, // try using the code in this comment block instead String portName = null; for(int n=1; n<10; n++) { portName = "COM" + n; SerialPort port = new SerialPort(portName); try { port.open(); port.close(); break; } catch(Exception exn) {} } return portName;*/ for (String portName : portNames) { SerialPort port = new SerialPort(portName); try { port.open(); port.close(); return portName; } catch (Exception exn) { } } return null; }
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()); }