java - 尝试使用 eclipse 从 Arduino 读取数据时收到不完整的消息?

标签 java eclipse arduino communication

我在使用 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/

相关文章:

java - 如何使用当前代码写入文件的新行?

Java Keystore 密码没意义?

java - 用数学方法计算十进制到二进制(java)

android - 点击按钮时如何制作小闪光灯?

java - Drools 文件未找到异常

c++ - 使用别人的库,该库在名称中具有值

serial-port - 用串行通信开始新的线路

java - 如何在 Vertica 中添加一天

java - 在 Eclipse 中打开项目

c++ - 如何在 Linux 上通过 C++ 串行接口(interface)与 Arduino 通信?