我正在尝试从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);


                }
            }


现在竞争String变量数据

07-24 09:44
查看更多