Wednesday, October 10, 2012

Arduino + Processing: Automatic Serial Port Selection

I find that using Bluetooth to connect an Arduino with Processing on a MacBook can be frustrating. The serial port number tends to jump around on me as I disconnect and reconnect. Since I want the first port on the serial list with my Arduino's name, I scan the list backwards - counting down in the 'for()' loop - using 'indexOf()' to search each line for the Arduino's name. If the line contains the text I'm looking for, that line number becomes the chosen port number. Once I've checked each port, the last port number assigned is the first Arduino on the list.

 import processing.serial.*;  
 Serial dreadPort;  
 String[] serialString;  
 String serialCheck;  
 String portName = "DreaduinoBluetooth";  
 int portNumber;  
 int serialIndex;  
 void setup() {
  dreadPort = new Serial(this, Serial.list()[portNumber], 115200);  
 void draw() {  
 void findSerialPort() {
  serialString = Serial.list();  
  for (int i = serialString.length - 1; i > 0; i--) {  
   serialCheck = serialString[i];  
   serialIndex = serialCheck.indexOf(portName);  
   if (serialIndex > -1) portNumber = i;  

No comments:

Post a Comment