通过USB从Arduino接收数据到Android设备

时间:2014-07-09 10:34:20

标签: android arduino usb

我正在尝试从Arduino接收数据到我的Android设备。我从here开始 在应用程序的活动部分,他们做了

@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if(fromUser){
if(sUsbController != null){
sUsbController.send((byte)(progress&0xFF));
      }
   }
}

在发送功能

public void send(byte data) {
    mData = data;
    synchronized (sSendLock) {
        sSendLock.notify();
    }
}

在UsbRunnable部分

private class UsbRunnable implements Runnable {
    private final UsbDevice mDevice;

    UsbRunnable(UsbDevice dev) {
        mDevice = dev;
    }

    @Override
    public void run() {//here the main USB functionality is implemented
        UsbDeviceConnection conn = mUsbManager.openDevice(mDevice);
        if (!conn.claimInterface(mDevice.getInterface(1), true)) {
            return;
        }
        // Arduino Serial usb Conv
        conn.controlTransfer(0x21, 34, 0, 0, null, 0, 0);
        conn.controlTransfer(0x21, 32, 0, 0, new byte[] { (byte) 0x80,
                0x25, 0x00, 0x00, 0x00, 0x00, 0x08 }, 7, 0);
...
...

conn.bulkTransfer(epOUT, new byte[] { mData }, 1, 0);

因此,App取得了搜索栏的进度并将其发送给了Arduino。 但是,我希望我的应用程序从Arduino接收数据。我想我也需要使用bulktransfer功能。认为我想将数据保存到mData变量。 我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

使用bulkTransfer方法是可行的方法。您需要使用IN端点来接收数据。例如,要从Arduino获取一个字节的数据,请使用:

byte[] reply = new byte[1]; // to store data from Arduino
int size = 1;               // receive at most 1 byte of data
int timeout = 100;          // try to receive data for up to 100 milliseconds
int count = conn.bulkTransfer(epIN, reply, size, timeout);

if(count < 0) {
    Log.d("ArduinoUSB", "Failure occurred when receiving from Arduino");
} else {
    Log.d("ArduinoUSB", "Received " + count + " bytes: " + Arrays.toString(reply));
} 

数据将存储在reply