【问题标题】:Getting incomplete messages when trying to read from Arduino with eclipse?尝试使用 Eclipse 从 Arduino 读取时收到不完整的消息?
【发布时间】:2017-07-11 20:29:18
【问题描述】:

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

【问题讨论】:

  • 我忘了说,我从 arduino 接口输入的输入流是“这是一个测试”,我得到的输出是“nullthis is a”和“nulla test”或只是“null”

标签: java eclipse arduino communication


【解决方案1】:

不可能知道何时数据将可用,也不可能是否输入数据将一次性全部可用而不是多个块可用。

这是一个快速而肮脏的修复

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

每次在串行输入数据中遇到\noutputString的内容首先打印在标准输出上,然后清除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多