代码之家  ›  专栏  ›  技术社区  ›  Boker

如果5秒后没有得到数据,关闭串口

  •  -1
  • Boker  · 技术社区  · 4 年前

    以下是我在课堂上的方法:

        public void initialize() throws Exception {
    
        CommPortIdentifier portId = CommPortIdentifier.getPortIdentifier(PORT_NAME);
    
        if (portId.isCurrentlyOwned()) {
            System.out.println("Error: Port is currently in use");
        } else {
                CommPort commPort = portId.open(this.getClass().getName(), TIME_OUT);
    
                serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
                        SerialPort.PARITY_NONE);
    
                input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
    
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);
        }
    }
    
    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }
    
    public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                input.ready();
                String data= input.readLine();
                System.out.println(data);
                close();
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
    
    0 回复  |  直到 4 年前
    推荐文章