通信Android与Arduino缓冲区不完整

时间:2015-02-23 22:56:57

标签: java android arduino buffer

我试图将一些数据从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。但从来没有完整的字符串。

我不知道出了什么问题。请帮忙。谢谢。

1 个答案:

答案 0 :(得分:1)

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

希望这有帮助。

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

  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);


                }
            }

现在控制String变量数据