Finding string to address serial port dynamically

試著忘記壹切 提交于 2020-01-05 11:49:43

问题


I have an application developed in Java, and a second under development in Ruby on Rails, which require connecting to Arduino by serial communication. While I can input a string based on my own computer to address the correct serial port, the string changes depending even on which USB port I use, which makes me think it would be better for the user to be able to select a valid serial port from one that is scanned from a list on their own computers, not one predefined by me. Does anyone have a strategy I can use for allowing the user to scan their computer for all serial ports and select the correct one out of an array/list, either in Java or Ruby on Rails?


回答1:


From 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);
      }
    }
  }
}


来源:https://stackoverflow.com/questions/24644789/finding-string-to-address-serial-port-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!