从 Arduino UNO R3 套件读取数据

Reading data from Arduino UNO R3 kit

我正在尝试读取我已经存储在 Arduino 套件 中的数据,我正在使用 physicaloid 库 来做到这一点。我通过使用 Arduino 本身提供的 B 型 USB 电缆 并使用 Tera Term 将其连接到我的 PC 来测试该套件(读取数据)。我在键盘上按“@”后开始传输数据(特定于我们的实现)。

但是当我将它连接到我的 Android 平板电脑并使用 physicaloid 的测试项目打开设备并开始通信时,每次我单击 'open' 它都会显示一个 Toast 说它无法打开。每次提示我时,我都允许访问 USB 设备。这是我为读取数据而创建的示例程序:

if(mPhysicaloid.open()){

        Toast.makeText(getBaseContext(), "communicating", Toast.LENGTH_SHORT).show();
        String signalToStart = new String("@");
        byte[] bufToWrite = signalToStart.getBytes();
        mPhysicaloid.write(bufToWrite, bufToWrite.length);

        byte[] buf = new byte[255];
        mPhysicaloid.read(buf);
        String data = new String(buf);
        tvResult.setText(data);
        mPhysicaloid.close();

    }
    else 
        Toast.makeText(getBaseContext(), "no communication with device", Toast.LENGTH_LONG).show();

现在我想知道来自 Arduino USB 数据线的数据:它是 RS232 格式吗? Android 设备无法理解(我不知道,我问这种数据格式可能犯了一个错误)还是 USB 数据格式适合Android设备了解吗?请帮忙,我整天都在搜索这个。我该怎么做才能打开设备并进行通信?

我终于想到了从串行USB设备读取数据。所以我想分享一下:

首先,获取所有连接的 USB 设备(如果有多个)并获取合适的接口并搜索要与之通信的端点。在初始化 USB 设备时,请确保您考虑了您真正想要与之通信的 USB 设备。您可以通过考虑产品 ID 和供应商 ID 来做到这一点。 执行上述操作的代码..

private boolean searchEndPoint() {

    usbInterface = null;//class level variables, declare these.
    endpointOut = null;
    endpointIn = null;

    Log.d("USB","Searching device and endpoints...");

    if (device == null) {
        usbDevices = usbManager.getDeviceList();
        Iterator<UsbDevice> deviceIterator = usbDevices.values().iterator();

        while (deviceIterator.hasNext()) {
            UsbDevice tempDevice = deviceIterator.next();

            /**Search device for targetVendorID(class level variables[vendorId = SOME_NUMBER and productId=SOME_NUMBER] which u can find) and targetProductID.*/
            if (tempDevice .getVendorId() == vendorId) {
                if (tempDevice .getProductId() == productId) {
                    device = tempDevice ;
                }                                                                                                                                                                                                                                                                                                                                                                
            }
        }
    }

    if (device == null){ 
        Log.d("USB","The device with specified VendorId and ProductId not found");
        return false;
    }

    else
        Log.d("USB","device found");

    /**Search for UsbInterface with Endpoint of USB_ENDPOINT_XFER_BULK,
     *and direction USB_DIR_OUT and USB_DIR_IN
     */
    try{
        for (int i = 0; i < device.getInterfaceCount(); i++) {
            UsbInterface usbif = device.getInterface(i);

            UsbEndpoint tOut = null;
            UsbEndpoint tIn = null;

            int tEndpointCnt = usbif.getEndpointCount();
            if (tEndpointCnt >= 2) {
                for (int j = 0; j < tEndpointCnt; j++) {
                    if (usbif.getEndpoint(j).getType() == UsbConstants.USB_ENDPOINT_XFER_BULK) {
                        if (usbif.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_OUT) {
                            tOut = usbif.getEndpoint(j);
                        } else if (usbif.getEndpoint(j).getDirection() == UsbConstants.USB_DIR_IN) {
                            tIn = usbif.getEndpoint(j);
                        }
                    }
                }

                if (tOut != null && tIn != null) {
                    /** This interface have both USB_DIR_OUT
                     * And USB_DIR_IN of USB_ENDPOINT_XFER_BULK
                     */
                    usbInterface = usbif;
                    endpointOut = tOut;
                    endpointIn = tIn;
                }
            }

        }

        if (usbInterface == null) {
            Log.d("USB","No suitable interface found!");
            return false;
        } else {
            Log.d("USB","Suitable interface found!");
            return true;
        }



    }catch(Exception ex){

        ex.printStackTrace();
        return false;
    }
}

现在您已准备好进行通信的设备、USB 接口和端点。现在是时候在您的 Android 设备和 USB 设备之间建立连接了。 以下是此代码(并检查连接是否已启动并正在通信):

private boolean checkUsbCOMM() {

    /**Value for setting request, on the USB connection.*/
    final int RQSID_SET_CONTROL_LINE_STATE = 0x22;

    boolean success = false;

    Log.d("USB","Checking USB Device for communication: ");
    try{

        Boolean permitToRead = SUSBS_usbManager.hasPermission(SUSBS_device);

        if (permitToRead) {
             //class level variable(connection, usbManager : declare it)
            connection = usbManager.openDevice(device);

            if (connection != null) {
                connection.claimInterface(usbInterface, true);

                int usbResult;

                usbResult = connection.controlTransfer(0x21,  //requestType
                        RQSID_SET_CONTROL_LINE_STATE,               //SET_CONTROL_LINE_STATE(request)
                        0,                                          //value
                        0,                                          //index
                        null,                                       //buffer
                        0,                                          //length
                        500);                                       //timeout = 500ms


                Log.i("USB","controlTransfer(SET_CONTROL_LINE_STATE)[must be 0 or greater than 0]: "+usbResult);

                if(usbResult >= 0)
                    success = true;
                else 
                    success = false;

            }

        }

        else {
            /**If permission is not there then ask for permission*/
            usbManager.requestPermission(device, mPermissionIntent);
            Log.d("USB","Requesting Permission to access USB Device: ");

        }

        return success;

    }catch(Exception ex){

        ex.printStackTrace();
        return false;
    }

}

瞧,USB 设备现在可以通信了。因此,让我们使用单独的线程阅读:

if(device!=null){
Thread readerThread = new Thread(){

                public void run(){

                    int usbResult = -1000;
                    int totalBytes = 0;

                    StringBuffer sb = new StringBuffer();
                    String usbReadResult=null;
                    byte[] bytesIn ;

                    try {

                        while(true){
                            /**Reading data until there is no more data to receive from USB device.*/
                            bytesIn = new byte[endpointIn.getMaxPacketSize()];
                            usbResult = connection.bulkTransfer(endpointIn, 
                                    bytesIn, bytesIn.length, 500);

                            /**The data read during each bulk transfer is logged*/
                            Log.i("USB","data-length/read: "+usbResult);

                            /**The USB result is negative when there is failure in reading or
                             *  when there is no more data to be read[That is : 
                             *  The USB device stops transmitting data]*/
                            if(usbResult < 0){
                                Log.d("USB","Breaking out from while, usb result is -1");
                                break;

                            }

                            /**Total bytes read from the USB device*/
                            totalBytes = totalBytes+usbResult;
                            Log.i("USB","TotalBytes read: "+totalBytes);

                            for(byte b: bytesIn){

                                if(b == 0 )
                                    break;
                                else{
                                    sb.append((char) b);
                                }


                            }

                        }

                        /**Converting byte data into characters*/
                        usbReadResult = new String(sb);
                        Log.d("USB","The result: "+usbReadResult);
                        //usbResult holds the data read.

                    } catch (Exception ex) {

                        ex.printStackTrace();
                    }


                }

            };

            /**Starting thread to read data from USB.*/
            SUSBS_readerThread.start();
            SUSBS_readerThread.join();


        }

要获得权限,请确保添加 PendingIntent 并将权限添加到您的清单中。

Android清单:<uses-feature android:name="android.hardware.usb.host" />

待定意向:

private PendingIntent mPermissionIntent;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
mPermissionIntent = PendingIntent.getBroadcast(MainActivity.this,
            0, new Intent(ACTION_USB_PERMISSION), 0);

    /**Setting up the Broadcast receiver to request a permission to allow the APP to access the USB device*/
    IntentFilter filterPermission = new IntentFilter(ACTION_USB_PERMISSION);
    registerReceiver(mUsbReceiver, filterPermission);