2013-03-11 126 views
-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线插回时,我的程序如何识别它被再次插入并串行通信?

+0

那么问题是什么?如何编写一个带有重试的循环? – EJP 2013-03-11 03:23:45

+0

@EJP,我再次编辑帖子。但是,我的问题的第一部分是我如何创建一条消息,让程序用户知道USB是否被拔出,然后如果它重新插入,消息就会消失,程序会继续,如果没有任何事情发生。 – Patrick 2013-03-11 13:46:28

回答

1

当你断开arduino的连接时,你应该以一种你认为合适的方式处理的运行时异常结束。找到引发异常的地方,将public void initialize更改为public boolean initialize,当进行连接时返回true。处理异常时继续调用initialize,直到它返回true。这只是一种做法。

相关问题