-1
我正在使用串行數據編寫一個java程序。我很好奇我如何才能解決一個問題,即我的arduino斷開連接,因此停止串行數據,然後重新連接,無需任何人工干預即可重新開始發送數據。在沒有用戶交互的情況下在Java中重新連接串口
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線插回時,我的程序如何識別它被再次插入並串行通信?
那麼問題是什麼?如何編寫一個帶有重試的循環? – EJP 2013-03-11 03:23:45
@EJP,我再次編輯帖子。但是,我的問題的第一部分是我如何創建一條消息,讓程序用戶知道USB是否被拔出,然後如果它重新插入,消息就會消失,程序會繼續,如果沒有任何事情發生。 – Patrick 2013-03-11 13:46:28