使用ASCII发送命令到USB端口

时间:2016-09-11 23:27:56

标签: java command usb

我需要向USB设备发送命令。我尝试了很多例子,但没有结果。我不知道问题是在命令结构中还是发送命令。 结构如下\ x1B COMMAND \ n(命令和标记之间没有空格)。

感谢您提出任何建议或更好的解决方案

public static void main(String[] args) {

    char ESC = (char) 27;
    char LN = (char) 10;
    String cmd = "command";
    String cmdString = ESC + cmd + LN;

    portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements()) {
        portId = (CommPortIdentifier) portList.nextElement();
        System.out.println(portList);
        if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            if (portId.getName().equals("/dev/ttyUSB0")) {

                try {
                    serialPort = (SerialPort) portId.open("SimpleWriteApp", 2000);
                } catch (PortInUseException e) {

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

                }
                try {
                    serialPort.setSerialPortParams(57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                            SerialPort.PARITY_NONE);
                } catch (UnsupportedCommOperationException e) {
                    ;
                }
                try {
                    outputStream.write(cmdString.getBytes());
                    outputStream.flush();

                } catch (IOException e) {

                }
            }
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

问题解决了。我使用了库JSSC https://github.com/scream3r/java-simple-serial-connector 有简单的源代码:

public static void main(String[] args) {
    char ESC = (char) 27; // Ascii character for Escape
    char LN = (char) 10;
    String message = "TX ENROLL:0 PGX:0 PGY:0 ALARM:0 BEEP:NONE";
    String cmd = ESC + message + LN;
    SerialPort serialPort = new SerialPort("/dev/ttyUSB0");
    try {

        serialPort.openPort();
        serialPort.setParams(SerialPort.BAUDRATE_57600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                SerialPort.PARITY_NONE);
        serialPort.writeString(cmd);

        serialPort.closePort();
    } catch (SerialPortException ex) {
        System.out.println(ex);
    }
}