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

我正在尝试通过 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


潇潇雨雨
浏览 103回答 1
1回答

精慕HU

如果您想编写仅打印您获得的字节的代码,我会尝试以下操作:if (uartDevice != null) {&nbsp; &nbsp; // Loop until there is no more data in the RX buffer.&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; byte[] buffer = new byte[CHUNK_SIZE];&nbsp; &nbsp; &nbsp; &nbsp; int read;&nbsp; &nbsp; &nbsp; &nbsp; while ((read = uartDevice.read(buffer, buffer.length)) > 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < read; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.printf("%02x", buffer[i]);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } catch (IOException e) {&nbsp; &nbsp; &nbsp; &nbsp; Log.w(TAG, "Unable to transfer data over UART", e);&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println();&nbsp; // Adds a newline after all bytes}以下是一个方法,该方法采用 aUartDevice作为参数,从它读取直到结束并返回byte包含全部内容的单个数组。不需要保证保存全部内容的任意缓冲区。返回的数组与它需要的大小完全一样。仅使用较小的读取缓冲区来提高性能。错误处理被忽略。这假设数据不大于内存所能容纳的大小。byte[] readFromDevice(UartDevice uartDevice) {&nbsp; &nbsp; byte[] buffer = new byte[CHUNK_SIZE];&nbsp; &nbsp; int read;&nbsp; &nbsp; ByteArrayOutputStream data = new ByteArrayOutputStream();&nbsp; &nbsp; while ((read = uartDevice.read(buffer, buffer.length)) > 0) {&nbsp; &nbsp; &nbsp; &nbsp; data.write(buffer, 0, read);&nbsp; &nbsp; }&nbsp; &nbsp; return data.toByteArray();}当所有数据都被读取后,该方法返回,您可以随意处理返回的数组。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java