从串行端口读取时接收截断的数据

Receiving truncated data while reading from Serial Port

我正在尝试通过 Uart 在 Arduino 和 Android 之间建立通信。因此,在 Android 端读取缓冲区时,我没有获取块中的数据。

 if (uartDevice != null) {
        // Loop until there is no more data in the RX buffer.
        try {
            byte[] buffer = new byte[CHUNK_SIZE];
            int read;
            while ((read = uartDevice.read(buffer, buffer.length)) > 0) {
                data = new String(buffer, StandardCharsets.UTF_8).substring(0, read);
                System.out.println(String.format("%020x", new BigInteger(1, data.getBytes(/*YOUR_CHARSET?*/))));

        } catch (IOException e) {
            Log.w(TAG, "Unable to transfer data over UART", e);
        }

预期输出为: 2a3619010101001a0708403031301010011214084030313010100112140845

相反,我收到了:

2a361a010101001a070840303130101001121408403031

8403031301010011214084030313010100112140845

3031301010011214084030313010100112140845

如果你想编写只打印你得到的字节的代码,我会尝试以下方法:

if (uartDevice != null) {
    // Loop until there is no more data in the RX buffer.
    try {
        byte[] buffer = new byte[CHUNK_SIZE];
        int read;
        while ((read = uartDevice.read(buffer, buffer.length)) > 0) {
            for (int i = 0; i < read; i++) {
                System.out.printf("%02x", buffer[i]);
            }
        }
    } catch (IOException e) {
        Log.w(TAG, "Unable to transfer data over UART", e);
    }
    System.out.println();  // Adds a newline after all bytes
}

以下是一个方法,它以 UartDevice 作为参数,从中读取直到结束,然后 returns 一个包含全部内容的 byte 数组。不需要保证保存全部内容的任意缓冲区。返回的数组正好和它需要的一样大。只使用一个小的读取缓冲区来提高性能。忽略错误处理。

这假设数据不大于它适合内存的大小。

byte[] readFromDevice(UartDevice uartDevice) {
    byte[] buffer = new byte[CHUNK_SIZE];
    int read;
    ByteArrayOutputStream data = new ByteArrayOutputStream();

    while ((read = uartDevice.read(buffer, buffer.length)) > 0) {
        data.write(buffer, 0, read);
    }

    return data.toByteArray();
}

方法returns读取完所有数据后,您可以随意处理返回的数组。