シリアルデータを使用して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 コードを再び差し込むと、プログラムはそれが再び差し込まれ、シリアル通信していることをどのように認識できますか?