我正在使用串行数据编写一个 java 程序。我很好奇如何解决我的 arduino 断开连接的问题,因此停止串行数据,然后再次连接到它,它将再次开始发送数据而无需任何人工交互。
public void initialize() {
working = 1;
CommPortIdentifier portId = null;
Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();
while (portEnum.hasMoreElements()) {
CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
for (String portName : PORT_NAMES) {
if (currPortId.getName().equals(portName)) {
portId = currPortId;
break;
}
}
}
if (portId == null) {
thirdDC = "Could not find COM Port. Error";
System.out.println(thirdDC);
return;
}
try {
serialPort = (SerialPort) portId.open(this.getClass().getName(),
TIME_OUT);
serialPort.setSerialPortParams(DATA_RATE,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
output = serialPort.getOutputStream();
serialPort.addEventListener(this);
serialPort.notifyOnDataAvailable(true);
System.out.println("WORKING");
} catch (Exception e) {
System.err.println(e.toString() + "NOPE");
}
}
public synchronized void close() {
if (serialPort != null) {
serialPort.removeEventListener();
serialPort.close();
}
}
public synchronized void serialEvent(SerialPortEvent oEvent) {
String stop = "ERROR";
if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
serialI = true;
try {
inputLine=input.readLine();
if (inputLine.equals(y)){
System.out.println(y);
temp1 = "OFF";
value = 0;
}
if (inputLine.equals(z)){
System.out.println(z);
temp1 = "ON";
value = 0;
}
if (inputLine.equals(stop)){
System.out.println(stop);
temp = "ERROR";
value = 1;
}
x = Double.parseDouble(inputLine);
if (x > 0){
temp = inputLine;
System.out.println(x);
value = 0;
}
} catch (Exception e) {
}
}else{
}
}
上面的代码是我认为需要编辑的方法。所以我的问题是,当我拔下 USB 线时,如何同时关闭串口?然后,当我重新插入 USB 线时,我的程序如何识别它已再次插入并正在串行通信?