2015-10-05 58 views
0

我從this網站使用此代碼,但是我沒有在控制檯上輸出任何內容。任何人都可以幫我解決問題嗎?使用Javax.comm從COM4獲取數據

import java.io.*; 
import java.util.*; 
import javax.comm.*; 

public class SimpleRead implements Runnable, SerialPortEventListener { 
    static CommPortIdentifier portId; 
    static Enumeration portList; 

    InputStream inputStream; 
    SerialPort serialPort; 
    Thread readThread; 

    public static void main(String[] args) { 
     portList = CommPortIdentifier.getPortIdentifiers(); 

     while (portList.hasMoreElements()) { 
      portId = (CommPortIdentifier) portList.nextElement(); 
      if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { 
       if (portId.getName().equals("COM4")) { 
      //    if (portId.getName().equals("/dev/term/a")) { 
        SimpleRead reader = new SimpleRead(); 
       } 
      } 
     } 
    } 

    public SimpleRead() { 
     try { 
      serialPort = (SerialPort) portId.open("SimpleReadApp", 2000); 
     } catch (PortInUseException e) {System.out.println(e);} 
     try { 
      inputStream = serialPort.getInputStream(); 
     } catch (IOException e) {System.out.println(e);} 
    try { 
      serialPort.addEventListener(this); 
    } catch (TooManyListenersException e) {System.out.println(e);} 
     serialPort.notifyOnDataAvailable(true); 
     try { 
      serialPort.setSerialPortParams(9600, 
       SerialPort.DATABITS_8, 
       SerialPort.STOPBITS_1, 
       SerialPort.PARITY_NONE); 
     } catch (UnsupportedCommOperationException e) {System.out.println(e);} 
     readThread = new Thread(this); 
     readThread.start(); 
    } 

    public void run() { 
     try { 
      Thread.sleep(20000); 
     } catch (InterruptedException e) {System.out.println(e);} 
    } 

    public void serialEvent(SerialPortEvent event) { 
     switch(event.getEventType()) { 
     case SerialPortEvent.BI: 
     case SerialPortEvent.OE: 
     case SerialPortEvent.FE: 
     case SerialPortEvent.PE: 
     case SerialPortEvent.CD: 
     case SerialPortEvent.CTS: 
     case SerialPortEvent.DSR: 
     case SerialPortEvent.RI: 
     case SerialPortEvent.OUTPUT_BUFFER_EMPTY: 
      break; 
     case SerialPortEvent.DATA_AVAILABLE: 
      byte[] readBuffer = new byte[20]; 

      try { 
       while (inputStream.available() > 0) { 
        int numBytes = inputStream.read(readBuffer); 
       } 
       System.out.print(new String(readBuffer)); 
      } catch (IOException e) {System.out.println(e);} 
      break; 
     } 
    } 
} 

這就是控制檯上的輸出的樣子。

enter image description here

我相信,我的COM端口是4和所有其他細節。我只是不知道它被終止的原因是什麼。

回答

0

那麼,我們可以看到, ,你沒有得到任何異常,你沒有數據可讀。

嘗試在代碼中調試或放置一些System.out.println,以執行該操作。