26 1 / 2014

I’ve been playing around with serial ports a lot lately in both Processing and Arduino. I wrote this little function to automatically select the correct port if you’re not entirely aware of the ID or name (just a fragment).

Hope this makes life easier for someone else too:

import processing.serial.*;

Serial xBee;

void setup()  {
  try {
    String serialPort = serialIndexFor("tty.usbserial");
    xBee = new Serial(this, serialPort, 9600);
  } catch (Exception e) {
    println(e);
    exit();
  }
}

String serialIndexFor(String name) throws Exception {
  for ( int i = 0; i < Serial.list().length; i ++ ) {
    String[] part = match(Serial.list()[i], name);
    if (part != null) {
      return Serial.list()[i];
    }
  }
  throw new Exception("Serial port named '" + name + "' could not be found");
}
  1. learning-arduino posted this