【问题标题】:Send command with ASCII to USB port将带有 ASCII 的命令发送到 USB 端口
【发布时间】:2017-01-19 09:04:50
【问题描述】:

我需要向 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) {

                }
            }
        }
    }
}

}

【问题讨论】:

    标签: java command usb


    【解决方案1】:

    问题已解决。我使用库 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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多