使用java通过usb-serial电缆连接

时间:2012-05-10 14:00:58

标签: java serial-port rxtx usbserial

我正在使用java库rxtxx将数据发送到微控制器  应用程序似乎工作,但出现警告:rxtxx2.1.7版本不匹配 它会影响发送的数据吗? 我测试了它但没有发送数据我的代码是:

    import java.util.*;
import gnu.io.*;
import java.io.*;



public class portwrit{
    static Enumeration        portList;
    static CommPortIdentifier portId;
   static String msgstr="100";
    static SerialPort         serialPort;
    static OutputStream       outputStream;
    static  InputStream inputStream;
    static  Thread readThread;


    static boolean        outputBufferEmptyFlag = false;

    public static void main(String[] args ) throws NoSuchPortException, PortInUseException {
    boolean portFound = false;
    String defaultPort = "COM6";


    portList = CommPortIdentifier.getPortIdentifiers();

    while (portList.hasMoreElements()) {
        portId = (CommPortIdentifier) portList.nextElement();

        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {

        if (portId.getName().equals(defaultPort)) {
            System.out.println("Found port " + defaultPort);
            portFound = true;
            try {
            serialPort = 
                (SerialPort) portId.open("SimpleWrite", 2000);
            } catch (PortInUseException e) {
            System.out.println("Port in use.");
            continue;
            } 

            try {
            outputStream = serialPort.getOutputStream();
            } catch (IOException e) {}

            try {
            serialPort.setSerialPortParams(9600, 
                               SerialPort.DATABITS_8, 
                               SerialPort.STOPBITS_1, 
                               SerialPort.PARITY_NONE);
            } catch (UnsupportedCommOperationException e) {}

            try {
                serialPort.notifyOnOutputEmpty(true);
            } catch (Exception e) {
            System.out.println("Error setting event notification");
            System.out.println(e.toString());
            System.exit(-1);
            }

            System.out.println(
                "Writing "+msgstr+"\" to "+serialPort.getName());
            try {
            outputStream.write(Byte.parseByte(msgstr));
            } catch (IOException e) {}

            try {
               Thread.sleep(2000);  // Be sure data is xferred before closing
            } catch (Exception e) {}
            serialPort.close();
            System.exit(1);

        } 
        } 
    } 

    if (!portFound) {
        System.out.println("port " + defaultPort + " not found.");
    } 
    } 


}

1 个答案:

答案 0 :(得分:0)

根据this article,您可能安装了多个RXTX软件副本。它建议在路径/类路径上查找comm.jar或RXTXcomm.jar或类似内容。