【问题标题】:java.io.IOException: Underlying input stream returned zero bytesjava.io.IOException:基础输入流返回零字节
【发布时间】:2017-09-13 09:53:35
【问题描述】:

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

我的问题:当我使用“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());
    }
}

【问题讨论】:

    标签: java arduino-uno ioexception serial-communication


    【解决方案1】:

    我使用的是serial.println,它最终打破了界限,而serial.write 没有。另一方面,java 的readLine() 方法读取整行,直到它重新识别换行符。(\n)

    问题:serial.write()的情况下,没有换行符“\n”,所以readLine()根本找不到任何行并导致java.io.IOException: Underlying input stream returned zero bytes readLine() 至少需要一个换行符才能工作。

    解决方法:在使用serial.write()时手动提供换行语句("\n")

    【讨论】:

      猜你喜欢
      • 2013-09-13
      • 2013-12-24
      • 1970-01-01
      • 2022-12-12
      • 1970-01-01
      • 1970-01-01
      • 2010-10-28
      • 2018-01-02
      • 1970-01-01
      相关资源
      最近更新 更多