java.io.IOException:底层输入流返回零字节

时间:2017-09-13 09:53:36

标签: java arduino-uno ioexception serial-communication

我试图在rxtx库的帮助下使用java程序读取arduino uno数据。我为此使用COM8串行通信端口。我使用win10。

我的问题:当我使用' serial.print',然后关闭java函数正常工作并检索arduino发送的所有内容。但是当我尝试使用' serial.write'在arduino然后发生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());
    }
}

1 个答案:

答案 0 :(得分:0)

我正在使用serial.println最后打破了这一行,而serial.write却没有。另一方面,java的readLine()方法读取整行,直到它记录换行符。(\ n)

问题:如果是serial.write(),则没有换行符&#34; \ n&#34;,因此readLine()无法找到任何行和结果java.io.IOException: Underlying input stream returned zero bytes readLine()工作需要至少一个换行符。

解决方案,同时使用serial.write()手动提供换行符声明(&#34; \ n&#34;)

相关问题