与 Arduino 缓冲区的通信 Android 未完成

Communication Android with Arduino Buffer incomplete

我正在尝试将一些数据从 Arduino 发送到 Android 设备,我看到了一些示例,但通信是从 Android 到 Arduino,但我想接收一些数据示例:

Serial.write("holamundo"); 

通过 OTG,连接成功,但我遇到了一些问题。

  @Override
public void run() {
    ByteBuffer buffer = ByteBuffer.allocate(100);
    UsbRequest request = new UsbRequest();
    request.initialize(usbDeviceConnection, endpointIn);
    try{
        while (true) {
            request.queue(buffer, 100);
            if (usbDeviceConnection.requestWait() == request) {
                byte [] bytearray = buffer.array();
                mgsfinal = new String(bytearray, Charset.forName("UTF-8"));

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(mgsfinal.length()>0){
                            serialText.setText("Bytes: " +mgsfinal); // for UTF-8 encoding);

                        }

                    }
                });
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
            } else {
                break;
            }
        }

    }catch(Exception e){
        etemp = e;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                serialText.setText("Bytes: " +etemp.getCause().toString()); // for UTF-8 encoding);

            }
        });
    }
}

我在第一次迭代中接收 "hol",然后我接收 "hola",然后 hol。但从来没有完整的字符串。

我不知道怎么了。请帮忙。谢谢。

经过几天的调查,我找到了解决方案。

希望对您有所帮助。

设置此项使通信正常并接受数据。

  usbDeviceConnection = connection;
  usbDeviceConnection.claimInterface(usbInterfaceFound, true);

  usbDeviceConnection.controlTransfer(0x21, 0x22, 0x1, 0, null, 0, 0);



// queue a request on the interrupt endpoint
            request.queue(buffer, buffer.capacity());
            // wait for status event
            if(usbDeviceConnection.requestWait() == request)
            {
                // there is no way to know how many bytes are coming, so simply forward the non-null values

                for(int i = 0; i < buffer.capacity() && buffer.get(i) != 0 ; i++)
                {
                    // transform ascii (0-255) to its character equivalent and append
                    dataByte = Character.toString((char) buffer.get(i));
                    data +=dataByte;
                    Log.e(this.getClass().getSimpleName(), "Was not able to read from USB device, ending listening thread ----> "+ data);


                }
            }

现在联系字符串变量数据