从Arduino的UNO R3套件读取数据 [英] Reading data from Arduino UNO R3 kit

查看:332
本文介绍了从Arduino的UNO R3套件读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读取已存储由我在的Arduino套件的数据,我使用了 physicaloid库以实现这一目标。我使用的 B型USB连接线按Arduino的本身,只要它连接到我的电脑,并使用万亿期限测试套件(读取数据)。该数据开始在键盘(具体到我们实现)后,我$ P $ @ PSS转移。

I'm trying to read the data already stored by me in the Arduino kit, I'm using the physicaloid library to achieve this. I tested the kit(reading data) by connecting it to my PC using the Type B USB cable provided by Arduino itself and using Tera Term. The data begins to transfer after i press @ in the keyboard(specific to our implementation).

但是,当我把它连接我的Andr​​oid平板电脑,并使用该测试项目由physicaloid打开设备并启动通信每次我点击打开它吐司无法打开,我允许访问它提示我的USB设备每次。这里是我创造了读取数据的示例程序

But when i connected it my Android tablet and using the test project by physicaloid to open a device and start communicating everytime i click open it Toast cannot open, i give permission to access the USB device everytime it prompts me. Here is the sample program which i had created to read the data

code:

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备考 T,其中Android设备无法理解(我不知道,我在这里可以做一个大错问这个数据格式)或者是在 USB数据格式(即适合和Android设备能够理解)。请帮助,我已搜查了这整整一天。我能做些什么来打开设备和交流。

Now what i want to know is that the data coming from the Arduino USB cable, is it in the RS232 format where the Android device is not able to understand(i dont know, i may be making a blunder here by asking this data format) or is it in the USB data format(that is suitable and the Android device is able to understand).Please help, i have searched over this the whole day. What can i do to open a the device and communicate.

推荐答案

我终于得到了读取串口USB设备中的数据的想法。所以思想的分享吧...

I finally got an idea of reading the data from serial USB device. So thought of sharing it...

1)首先获得所有连接的USB设备(如果不止一个),并得到一个合适的接口,并搜索终端进行通信。在初始化USB设备,请确保ü考虑其中U真的要与之通信的USB设备。 U可以做到这一点的考虑产品ID和供应商ID。 在code做上述..

1) first get all the USB devices attached(if more than one) and get a suitable interface and search for endpoints to communicate. While initializing the USB device make sure u consider the USB device which u really want to communicate with. U can do that by considering product id and Vendor id. The code for doing the above described..

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

现在u有一个装置,USB接口和端点做好通信准备。现在,它的时间来建立Android设备和USB设备之间的连接。 下面是code,这和检查连接是否和沟通:

Now u have a device, usb interface and endpoints ready for communication. Now its time to establish a connection between for Android device and USB device. Below is the code for this and check whether the connection is up and communicating:

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设备现在能够进行通信。因此,让我们阅读。 code:使用单独的线程读

Ola, the USB device is now able to communicate. So let us read. Code: Read using seperate thread

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


        }

最后一个:增加一个待定的意图许可,并在明显的提到这一点 清单:&LT;使用特征的android:NAME =android.hardware.usb.host/&GT;

last one : Adding a pending intent for permission and also in manifest mention this Manifest :<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);

完成完蛋了......

Finish thats it...

这篇关于从Arduino的UNO R3套件读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆