2017-09-13 187 views
1

我試圖在rxtx庫的幫助下使用java程序讀取arduino uno數據。我爲此使用COM8串行通信端口。我使用win10。java.io.IOException:底層輸入流返回零字節

我的問題是:當我使用'serial.print'時,然後向下的java函數正常工作,並檢索arduino發送的所有內容。但是當我嘗試在arduino中使用'serial.write'時,發生了ioexception 「java.io.IOException:底層輸入流返回零字節」 我不知道爲什麼。 我的需求是使用'serial.write'方法,請告訴我代碼中出了什麼問題。兩個代碼是向下

Java函數代碼:

public synchronized void serialEvent(SerialPortEvent oEvent) { 
     if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) { 
      try { 
       String inputLine=input.readLine(); 
       System.out.println(inputLine); 
      } catch (Exception e) { 
       System.err.println(e.toString()); 
      } 
     } 
     // Ignore all the other eventTypes, but you should consider the other ones. 
    } 

的Arduino UNO代碼:

#include <SoftwareSerial.h> 

SoftwareSerial mySerial(9, 10); 
void setup() { 
    mySerial.begin(9600); // Setting the baud rate of Software Serial Library 
    Serial.begin(9600); //Setting the baud rate of Serial Monitor 
} 
void loop() { 
    if(mySerial.available() > 0) { 
     Serial.print(mySerial.read()); 
    } 
} 

回答

0

我用serial.println打破到底線,而serial.write沒有。在另一側的java的readLine()方法讀取整個行,直到它recorgnizes換行符(\ n)的

問題:serial.write()情況下,不存在換行「\ n」個,所以readLine()根本無法找到任何線路,並且導致java.io.IOException: Underlying input stream returned zero bytes 無法爲readLine()工作發送一個換行符。

溶液:同時使用serial.write()手動提供線break語句( 「\ n」 個)