2014-07-09 22 views
1

我有一個用Java開發的應用程序,第二個用Ruby on Rails開發,需要通過串行通信連接到Arduino。儘管我可以根據自己的計算機輸入一個字符串來解決正確的串行端口問題,但字符串的更改取決於我使用的USB端口,這使我認爲用戶能夠選擇有效的串行端口會更好從一個從他們自己的計算機上的列表掃描而來的,而不是由我預定的。有沒有人有我可以用來允許用戶掃描他們的計算機的所有串行端口,並選擇一個數組/列表中正確的一個,在Java或Ruby on Rails的策略?查找字符串以動態地址串行端口

回答

0

List the ports

import java.util.Enumeration; 

import javax.comm.CommPortIdentifier; 

/** 
* List the ports. 
* 
* @author Ian F. Darwin, http://www.darwinsys.com/ 
* @version $Id: CommPortLister.java,v 1.4 2004/02/09 03:33:51 ian Exp $ 
*/ 
public class CommPortLister { 

    /** Simple test program. */ 
    public static void main(String[] ap) { 
    new CommPortLister().list(); 
    } 

    /** Ask the Java Communications API * what ports it thinks it has. */ 
    protected void list() { 
    // get list of ports available on this particular computer, 
    // by calling static method in CommPortIdentifier. 
    Enumeration pList = CommPortIdentifier.getPortIdentifiers(); 

    // Process the list. 
    while (pList.hasMoreElements()) { 
     CommPortIdentifier cpi = (CommPortIdentifier) pList.nextElement(); 
     System.out.print("Port " + cpi.getName() + " "); 
     if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL) { 
     System.out.println("is a Serial Port: " + cpi); 
     } else if (cpi.getPortType() == CommPortIdentifier.PORT_PARALLEL) { 
     System.out.println("is a Parallel Port: " + cpi); 
     } else { 
     System.out.println("is an Unknown Port: " + cpi); 
     } 
    } 
    } 
} 
+0

這段代碼是什麼,我一直在尋找,但該枚舉對象不與要素(getPortIdentifiers方法返回一個空枚舉)填充。有什麼想法嗎? – user3666782

+0

嗯。在時尚之後在這裏工作。這檯筆記本電腦號稱有兩個並行端口...: $ java的CommPortLister 端口LPT1是一個並行端口:[email protected] 端口LPT2是一個並行端口:[email protected] 錯誤2打開註冊表項HARDWARE \ DEVICEMAP \ SERIALCOMM – DavidPostill

+0

我使用了javaxcomm(http://en.sourceforge.jp/projects/sfnet_rcxtools/downloads/RCXTools/RCXTools%20v1.1/javaxcomm.zip/) – DavidPostill