2015-11-10 29 views
0

我正在嘗試創建一個與Arduino連接的處理應用程序。首先訪問/dev/cu.*端口時串行端口/dev/tty.*不工作

由於我希望自動建立兩者之間的連接,這意味着我不指定端口的名稱,但我使用Serial.list()來獲取端口的名稱可用,然後用for循環,我將檢查哪一個正在打印正確的字符串。

問題是,當我首先訪問/dev/cu.*時,所有的端口都是忙的,反之亦然。這很奇怪,我不希望發生這種情況。

回答

0

您應該能夠使用一個(/dev/tty.*)或其他(/dev/cu.*),但不能兩者都在同一時間,因爲他們可能會指向不同的方式相同的資源。

我推薦上市的端口,檢查端口前綴(agains假設/dev/tty.*,但不/dev/cu.*),初始化串行端口,然後退出橫穿上市串行端口的環路:

import processing.serial.*; 

Serial arduino; 
final int BAUD_RATE = 9600; 

void setup(){ 
    String[] ports = Serial.list(); 

    for(int i = 0 ; i < ports.length; i++){//go through each port 
    if(ports[i].contains("tty.usbmodem")){//find one that looks like an Arduino on OSX 

     try{ 
     arduino = new Serial(this,ports[i],BAUD_RATE);//initialize the connection 
     i = ports.length;//exit the loop, break; should also work 
     println("Arduino connection succesfully initialized"); 
     }catch(Exception e){ 
     System.err.println("Error opening Serial port!\nPlease check USB connection and ensure the port is not already open in another application."); 
     e.printStackTrace(); 
     } 

    } 
    } 

    if(arduino == null) System.err.println("Serial connection to Arduino failed!"); 
}