我在使用 arduino 时遇到一些问题。在类里面,我们正在学习arduino/java通信。因此,我们被要求解释从 arduino 发送的字节,并将其写在 Eclipse 的控制台中,就像消息的“键”告诉我们写入的任何类型一样。
到目前为止,我只是测试输入流,但我似乎无法获得完整的消息。这就是我正在做的事情:
public void run() throws SerialPortException {
while (true) {
if (port.available()) { //code written in another class, referenced below
byte byteArray[] = port.readByte(); //also code written in another class, referenced below
char magicNum = (char) byteArray[0];
String outputString = null;
for (int i = 0; i < byteArray.length; ++i) {
char nextChar = (char) byteArray[i];
outputString += Character.toString(nextChar);
}
System.out.println(outputString);
}
}
}
下面是上面代码中使用的另一个类的代码
public boolean available() throws SerialPortException {
if (port.getInputBufferBytesCount() == 0) {
return false;
}
return true;
}
public byte[] readByte() throws SerialPortException {
boolean debug= true;
byte bytesRead[] = port.readBytes();
if (debug) {
System.out.println("[0x" + String.format("%02x", bytesRead[0]) + "]");
}
return bytesRead;
}
最佳答案
不可能知道数据何时可用,也不可能知道输入数据是否一次性全部可用,而不是分成几个 block 。
这是一个快速但肮脏的修复:
public void run() throws SerialPortException {
String outputString = "";
while (true) {
if (port.available()) {
byte byteArray[] = port.readByte();
for (int i = 0; i < byteArray.length; ++i) {
char nextChar = (char) byteArray[i];
if (nextChar == '\n') {
System.out.println(outputString);
outputString = "";
}
outputString += Character.toString(nextChar);
}
}
}
}
outputString
的声明已移出,并为其分配了 ""
,以便摆脱标准输出上丑陋的 null
。
每次在串行输入数据中遇到\n
时,outputString
的内容首先打印在标准输出上,然后清除。
关于java - 尝试使用 eclipse 从 Arduino 读取数据时收到不完整的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42380500/