我试图在rxtx库的帮助下使用java程序读取arduino uno数据。为此,我使用了COM8串行通信端口。我在用win10。
我的问题是:当我使用‘erial.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());
}
}发布于 2017-11-03 06:38:26
我使用的是serial.println,它在最后打破了行,而serial.write没有。另一方面,java的readLine()方法读取整行,直到它记录了一个断行。(\n)
问题:在serial.write()的情况下,没有换行"\n",因此readLine()根本找不到任何行,因此导致java.io.IOException: Underlying input stream returned zero bytes atleasst -- readLine()需要一行中断才能工作。
解决方案:同时使用serial.write()手动提供换行语句(“\n”)
https://stackoverflow.com/questions/46194361
复制相似问题