Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
ello I try to connecet android with microconroller"8051" using USB ... the mobile should send byte[7] and directly recieve response from micro also byte[7]... I write the code and detect the device but the problem is when i try to send data the data loss and arrive to micro always zero even if i send {1,2,3,4,5,6,7} when the micro receive this data it arrive as {0,0,0,0,0,0,0} not {1,2,3,4,5,6,7} then no response form micro to mobile .... i try to send to different way but the same result always the data arrive to micro zero ""data loss or corrupted""" this my code on the first button I try to send data and receive it using thread on the second button i try to send data using normal way "bulk transfer"

thank alot for all


Java
UsbDevice deviceFound = null;
TextView textStatus;
TextView textresult;
String txt = "defaulr";
Button resetbtn;
Button sendbtn;
private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
PendingIntent mPermissionIntent;
UsbInterface usbInterfaceFound = null;
UsbInterface usbInterface;
UsbEndpoint endpointIn = null;
UsbEndpoint endpointOut = null;
UsbDeviceConnection usbDeviceConnection;

//30-11
String stringToRx;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textStatus = (TextView) findViewById(R.id.textStatus);
    textresult = (TextView) findViewById(R.id.resultxt);
    resetbtn = (Button) findViewById(R.id.resetbtn);
    sendbtn = (Button) findViewById(R.id.sendbtn);
    // register the broadcast receiver
    mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(
            ACTION_USB_PERMISSION), 0);
    IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
    registerReceiver(mUsbReceiver, filter);

    registerReceiver(mUsbDeviceReceiver, new IntentFilter(
            UsbManager.ACTION_USB_DEVICE_ATTACHED));
    registerReceiver(mUsbDeviceReceiver, new IntentFilter(
            UsbManager.ACTION_USB_DEVICE_DETACHED));

    connectUsb();

    resetbtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            //30-11-2014
            Thread threadSendData = new  Thread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    SendData();
                }
            });
            threadSendData.start();
        }
    });
    sendbtn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            try {
                int i =2;
                byte num = (byte) i;
                //byte[] SendData = { 0, 0, 0, 0, 0, 0, 0 };
                //byte[] SendData = { 4,num, num, 0, 0, 0, 4 };

                byte[] SendData = { 0, 2,3, 4, 5, 6, 7 };
                int dout = usbDeviceConnection.bulkTransfer(
                        endpointOut, SendData, SendData.length, 2000);

                Toast.makeText(getBaseContext(), "the data sent....",
                        Toast.LENGTH_LONG).show();

                StringBuilder sb = new StringBuilder(SendData.length * 2);
                   for(byte b: SendData)
                      sb.append(String.format("%02x", b & 0xff));
                    sb.toString();
                    textStatus.setText( sb);




                byte[] RecData = new byte[7];
                // byte[] RecData = new
                // byte[usbEndpointIn.getMaxPacketSize()];
                int din = usbDeviceConnection.bulkTransfer(endpointIn,
                        RecData, RecData.length, 2000);
                StringBuilder sr = new StringBuilder(RecData.length * 2);
                   for(byte b: RecData)
                      sr.append(String.format("%02x", b & 0xff));
                    sr.toString();
                    textStatus.setText( sr);
                Toast.makeText(getBaseContext(),
                        "the data Receive...."+din, Toast.LENGTH_LONG)
                        .show();

            } catch (Throwable e) {
                Toast.makeText(getBaseContext(), e.toString(),
                        Toast.LENGTH_LONG).show();
            }
        }
    });
}

 @Override
 protected void onDestroy() {
  releaseUsb();
  unregisterReceiver(mUsbReceiver);
  unregisterReceiver(mUsbDeviceReceiver);
  super.onDestroy();
 }





@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}


///30-11-2014
private void SendData()
{
    synchronized (this) 
    {
        if (deviceFound != null) 
        {
            int i =4;
            byte num = (byte) i;

            byte[] SendData = { 4, 2,3, 4, 5, 6, 7 };
            /*int dout = usbDeviceConnection.bulkTransfer(
                    endpointOut, SendData, SendData.length, 0);*/

            byte[] by = new byte[1];
            for(int j=0; i< SendData.length; j++)
            {
                 by[0] = SendData[j];
                 //Log.d(TAG, "sendArduinoTextb[0]: " + b[0]);
                 usbDeviceConnection.bulkTransfer(endpointOut,
                      by, 1, 0);
            }

            try {
                  Thread.sleep(100);
                 } catch (InterruptedException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                 }

            Toast.makeText(getBaseContext(), "the data sent....",
                    Toast.LENGTH_LONG).show();

            StringBuilder sb = new StringBuilder(SendData.length * 2);
               for(byte b: SendData)
                  sb.append(String.format("%02x", b & 0xff));
                sb.toString();
                textStatus.setText( sb);

        } 

    }
}

@Override
 public void run() {

  ByteBuffer buffer = ByteBuffer.allocate(1);
        UsbRequest request = new UsbRequest();
        request.initialize(usbDeviceConnection, endpointIn);
        while (true) {
            request.queue(buffer, 1);
            if (usbDeviceConnection.requestWait() == request) {
                byte dataRx = buffer.get(0);
              //  Log.d(TAG, "dataRx: " + dataRx);

                 stringToRx += (char)dataRx;
                 runOnUiThread(new Runnable(){

      @Override
      public void run() {
          textStatus.setText(stringToRx);
      }});

            } else {
                break;
            }
        }

 }



private void connectUsb() {

    textStatus.setText("connectUsb()");

    searchEndPoint();

    if (usbInterfaceFound != null) {
        setupUsbComm();
        Toast.makeText(getBaseContext(), "finsh Setup USBcommand....",
                Toast.LENGTH_LONG).show();
    }

}


  private void releaseUsb() {
    Toast.makeText(test.this, 
                "releaseUsb()", 
                Toast.LENGTH_LONG).show();
  textStatus.setText("releaseUsb()");

  if (usbDeviceConnection != null) { if (usbInterface != null) {
  usbDeviceConnection.releaseInterface(usbInterface); usbInterface = null;
  } usbDeviceConnection.close(); usbDeviceConnection = null; }

  deviceFound = null; usbInterfaceFound = null; endpointIn = null;
  endpointOut = null; 
  }


// usb related
private boolean setupUsbComm() {





    boolean success = false;

    UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
    Boolean permitToRead = manager.hasPermission(deviceFound);

    if (permitToRead) {
        usbDeviceConnection = manager.openDevice(deviceFound);
        if (usbDeviceConnection != null)
        {
            if(usbDeviceConnection.claimInterface(usbInterfaceFound, true))
                {
                Toast.makeText(getBaseContext(), "claim is ok ....",
                        Toast.LENGTH_LONG).show();



                usbDeviceConnection.controlTransfer(0x40, 0, 0, 0, null, 0, 0);//reset
                usbDeviceConnection.controlTransfer(0x40, 0, 1, 0, null, 0, 0);//clear Rx
                usbDeviceConnection.controlTransfer(0x40, 0, 2, 0, null, 0, 0);//clear Tx
                usbDeviceConnection.controlTransfer(0x40, 0x03, 0x0271, 0, null, 0, 0);//baudrate 4800


                }
            else
                {
                Toast.makeText(getBaseContext(), "Not claim  ....",
                        Toast.LENGTH_LONG).show();
                }




        }

    } 
    else {
        manager.requestPermission(deviceFound, mPermissionIntent);
        textStatus.setText("Permission: " + permitToRead);
    }

    return success;
}

private void searchEndPoint() {
    usbInterfaceFound = null;
    endpointOut = null;
    endpointIn = null;
    if (deviceFound == null) {
        UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
        HashMap<String, UsbDevice> deviceList = manager.getDeviceList();
        // UsbDevice device = deviceList.get("deviceName");

        Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
        while (deviceIterator.hasNext()) {
            UsbDevice device = deviceIterator.next();

            Toast.makeText(getBaseContext(),
                    "the data"+ device.getVendorId()+"..."+device.getProductId(), Toast.LENGTH_LONG).show();

            int Vendor = 4292;
            int productId = 60001;
            if (device.getVendorId() ==Vendor)
            {if (device.getProductId() ==productId)
            {
                textStatus.setText(device.getDeviceName());
                Toast.makeText(getBaseContext(),
                        "now connect ", Toast.LENGTH_LONG).show();
                deviceFound = device;
                    }
             }
        }
    }
    if (deviceFound == null) {
        textStatus.setText("device not found");
    } else {
        // Search for UsbInterface with Endpoint of USB_ENDPOINT_XFER_BULK,
        // and direction USB_DIR_OUT and USB_DIR_IN

        for (int i = 0; i < deviceFound.getInterfaceCount(); i++) {
            UsbInterface usbif = deviceFound.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
                    usbInterfaceFound = usbif;
                    endpointOut = tOut;
                    endpointIn = tIn;
                    //textStatus.setText("both direction");
                }
            }

        }
    }
}

private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (ACTION_USB_PERMISSION.equals(action)) {

            textStatus.setText("ACTION_USB_PERMISSION");

            synchronized (this) {
                UsbDevice device = (UsbDevice) intent
                        .getParcelableExtra(UsbManager.EXTRA_DEVICE);

                if (intent.getBooleanExtra(
                        UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    if (device != null) {
                        connectUsb();
                    }
                } else {
                    textStatus.setText("permission denied for device ");
                }
            }
        }
    }
};

private final BroadcastReceiver mUsbDeviceReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {

            deviceFound = (UsbDevice) intent
                    .getParcelableExtra(UsbManager.EXTRA_DEVICE);

            textStatus.setText("ACTION_USB_DEVICE_ATTACHED");

            connectUsb();

        } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {

            UsbDevice device = (UsbDevice) intent
                    .getParcelableExtra(UsbManager.EXTRA_DEVICE);

            textStatus.setText("ACTION_USB_DEVICE_DETACHED");

            if (device != null) {
                if (device == deviceFound) {
                 releaseUsb();
                    Toast.makeText(getBaseContext(), "release USB....",
                            Toast.LENGTH_LONG).show();
                }
            }

        }
    }

};
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900