2008-12-03 46 views
9

Tôi là người mới bắt đầu trong Java. Tôi đang đọc dữ liệu từ thiết bị thông qua cổng nối tiếp. Tôi nhận được dữ liệu cho mỗi một phút, nhưng lần đọc đầu tiên sắp đến một nửa, sau khi dữ liệu đó được gửi chính xác.Đọc cổng nối tiếp trong Java

Output tôi nhận được là:

6050.003120815340006050.003120815350006050.0

đầu ra đúng nên như thế này:

03120815340006050.003120815350006050.0


Mã của tôi là:

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

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

InputStream inputStream; 
SerialPort serialPort; 
Thread readThread; 
byte[] readBuffer; 

public static void main(String[] args) { 
    portList = CommPortIdentifier.getPortIdentifiers(); 
    System.out.println("portList... " + portList); 
    while (portList.hasMoreElements()) { 
     portId = (CommPortIdentifier) portList.nextElement(); 
     if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { 
      System.out.println("port identified is Serial.. " 
        + portId.getPortType()); 
      if (portId.getName().equals("COM2")) { 
       System.out.println("port identified is COM2.. " 
         + portId.getName()); 
       // if (portId.getName().equals("/dev/term/a")) { 
       SimpleRead reader = new SimpleRead(); 
      } else { 
       System.out.println("unable to open port"); 
      } 
     } 
    } 
} 

public SimpleRead() { 
    try { 
     System.out.println("In SimpleRead() contructor"); 
     serialPort = (SerialPort) portId.open("SimpleReadApp1111",500); 
     System.out.println(" Serial Port.. " + serialPort); 
    } catch (PortInUseException e) { 
     System.out.println("Port in use Exception"); 
    } 
    try { 
     inputStream = serialPort.getInputStream(); 
     System.out.println(" Input Stream... " + inputStream); 
    } catch (IOException e) { 
     System.out.println("IO Exception"); 
    } 
    try { 
     serialPort.addEventListener(this); 

    } catch (TooManyListenersException e) { 
     System.out.println("Tooo many Listener exception"); 
    } 
    serialPort.notifyOnDataAvailable(true); 
    try { 

     serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, 
       SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); 

     // no handshaking or other flow control 
     serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE); 

     // timer on any read of the serial port 
     serialPort.enableReceiveTimeout(500); 

     System.out.println("................"); 

    } catch (UnsupportedCommOperationException e) { 
     System.out.println("UnSupported comm operation"); 
    } 
    readThread = new Thread(this); 
    readThread.start(); 
} 

public void run() { 
    try { 
     System.out.println("In run() function "); 
     Thread.sleep(500); 
     // System.out.println(); 
    } catch (InterruptedException e) { 
     System.out.println("Interrupted Exception in run() method"); 
    } 
} 

public void serialEvent(SerialPortEvent event) { 

    // System.out.println("In Serial Event function().. " + event + 
    // event.getEventType()); 
    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: 
     readBuffer = new byte[8]; 

     try { 

      while (inputStream.available()>0) { 

       int numBytes = inputStream.read(readBuffer); 
      // System.out.println("Number of bytes read " + numBytes); 
      } 

      System.out.print(new String(readBuffer)); 

     } catch (IOException e) { 
      System.out.println("IO Exception in SerialEvent()"); 
     } 
     break; 
    } 
    // System.out.println(); 
/* String one = new String(readBuffer); 
    char two = one.charAt(0); 
    System.out.println("Character at three: " + two);*/ 
} 

} 
+0

Vui lòng thêm bốn khoảng trắng ở phía trước của dòng đầu tiên, để nó được định dạng dưới dạng mã. – guerda

+0

Bạn vừa sao chép từ trang web khác? - http://www.java-samples.com/showtutorial.php?tutorialid=11 –

Trả lời

2

này trông như thể bạn đang đọc phần còn lại của một số thông điệp được gửi trước khi bạn bắt đầu.

Cố gắng đọc càng nhiều dữ liệu càng tốt khi bạn khởi động chương trình để xóa mọi bộ đệm phần cứng. Sau đó, bắt đầu xử lý của bạn.

3

Thử xả bộ đệm đầu vào của cổng trước khi đọc. Nếu không, nếu kết thúc gửi đã gửi dữ liệu trong khi khởi động chương trình của bạn (hoặc gần trước đó, có thể là hệ điều hành), bạn sẽ nhận được dữ liệu đệm cũ. Ngoài ra, nếu có thể, hãy cân nhắc việc thêm khung thư vào giao thức, vì vậy bạn có thể phát hiện khi bạn đã đọc nội dung nào đó không thực sự là một thư hoàn chỉnh và loại bỏ thư đó. Điều này thường rất hữu ích với các loại vấn đề này.

4

Sử dụng như sau:

while (inputStream.available()>0) { 
    int numBytes = inputStream.read(readBuffer); 
    System.out.print(new String(readBuffer)); 
} 

Bạn đang in kết quả ra khỏi vòng lặp while. Tuy nhiên, mã bên trong vòng lặp có thể chạy nhiều lần, vì vậy đoạn dữ liệu sẽ bị mất.

+0

tôi đã thử mã ở trên nhưng phương thức serialEvent không được thực thi. Bạn có thể cho tôi biết tại sao không? –

Các vấn đề liên quan