【发布时间】: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) {
}
}
}
}
}
}
【问题讨论】: