Monday, June 3, 2013

Android code for Communication between Android and Arduino Due

It's the code in Android side for the example "Communication between Android and Arduino Due".

Communication between Android and Arduino Due
Communication between Android and Arduino Due


AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidadkcommunication"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="12"
        android:targetSdkVersion="17" />
    
    <uses-feature android:name="android.hardware.usb.accessory"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <uses-library android:name="com.android.future.usb.accessory"/>
        <activity
            android:name="com.example.androidadkcommunication.MainActivity"
            android:label="@string/app_name" 
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
            </intent-filter>
            <meta-data android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"
                android:resource="@xml/myfilter"/>
        </activity>
    </application>

</manifest>


/res/xml/myfilter.xml
<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <usb-accessory
        manufacturer="Arduino-er"
        model="AndroidADKCommunication"
        version="0.1"/>
</resources>


Layout file, /res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#E0E0E0"
        >       
        <TextView
            android:id="@+id/panelin"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </ScrollView>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:background="#D0D0D0">
        <Button 
            android:id="@+id/send"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:text="Send to Arduino"/>
        <EditText 
            android:id="@+id/textout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_above="@id/send"/>
    </RelativeLayout>

</LinearLayout>


Create a abstract class AbstractAdkActivity.java.
/*
 * abstract class for Activities have to read ADK
 * for android:minSdkVersion="12"
 * 
 */

package com.example.androidadkcommunication;

import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbAccessory;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;

public abstract class AbstractAdkActivity extends Activity {
 
 private static int RQS_USB_PERMISSION = 0;
 private static final String ACTION_USB_PERMISSION = "arduino-er.usb_permission";
 private PendingIntent PendingIntent_UsbPermission;
 
 private UsbManager myUsbManager;
 private UsbAccessory myUsbAccessory;
 private ParcelFileDescriptor myAdkParcelFileDescriptor;
 private FileInputStream myAdkInputStream;
 private FileOutputStream myAdkOutputStream;
 boolean firstRqsPermission;

 //do something in onCreate()
 protected abstract void doOnCreate(Bundle savedInstanceState);
 //do something after adk read
 //protected abstract void doAdkRead(String stringIn);
 protected abstract void doAdkRead_inBackGroundThread(int length, byte[] bfr);
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  //setContentView(R.layout.activity_main);
  
  myUsbManager = (UsbManager)getSystemService(Context.USB_SERVICE);
  IntentFilter intentFilter = new IntentFilter();
  intentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
  registerReceiver(myUsbReceiver, intentFilter);
  
  //Ask USB Permission from user
  Intent intent_UsbPermission = new Intent(ACTION_USB_PERMISSION);
  PendingIntent_UsbPermission = PendingIntent.getBroadcast(
    this,      //context
    RQS_USB_PERMISSION,  //request code
    intent_UsbPermission, //intent 
    0);      //flags
  IntentFilter intentFilter_UsbPermission = new IntentFilter(ACTION_USB_PERMISSION);
  registerReceiver(myUsbPermissionReceiver, intentFilter_UsbPermission);
  
  firstRqsPermission = true;
  doOnCreate(savedInstanceState);
 }
 
 @Override
 protected void onResume() {
  super.onResume();
  
  if(myAdkInputStream == null || myAdkOutputStream == null){
   
   UsbAccessory[] usbAccessoryList = myUsbManager.getAccessoryList();
   UsbAccessory usbAccessory = null;
   if(usbAccessoryList != null){
    usbAccessory = usbAccessoryList[0];
    
    if(usbAccessory != null){
     if(myUsbManager.hasPermission(usbAccessory)){
      //already have permission
      OpenUsbAccessory(usbAccessory);
     }else{
      
      if(firstRqsPermission){
       
       firstRqsPermission = false;
       
       synchronized(myUsbReceiver){
        myUsbManager.requestPermission(usbAccessory, 
          PendingIntent_UsbPermission);
       }
      }
      
     }
    }
   }
  }
 }
 
 //Write String to Adk
 void WriteAdk(String text){

  byte[] buffer = text.getBytes();

  if(myAdkOutputStream != null){
   
   try {
    myAdkOutputStream.write(buffer);
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   } 
  }
 }
 
 //Write a single byte to Adk
 void WriteByteAdk(byte oneByte){
  if(myAdkOutputStream != null){
   try {
    myAdkOutputStream.write(oneByte);
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }
 
 @Override
 protected void onPause() {
  super.onPause();
  closeUsbAccessory();
 }

 @Override
 protected void onDestroy() {
  super.onDestroy();
  unregisterReceiver(myUsbReceiver);
  unregisterReceiver(myUsbPermissionReceiver);
 }
 
 Runnable runnableReadAdk = new Runnable(){

  @Override
  public void run() {
   int numberOfByteRead = 0;
   final byte[] buffer = new byte[255];
   
   while(numberOfByteRead >= 0){
    
    try {
     
     numberOfByteRead = myAdkInputStream.read(buffer, 0, buffer.length);
     if(numberOfByteRead > 0){
      doAdkRead_inBackGroundThread(numberOfByteRead, buffer);
     }

    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
     break;
    }
   }
  }
  
 };
 
 private BroadcastReceiver myUsbReceiver = new BroadcastReceiver(){
  
  @Override
  public void onReceive(Context context, Intent intent) {

   String action = intent.getAction();
   if(action.equals(UsbManager.ACTION_USB_ACCESSORY_DETACHED)){

    UsbAccessory usbAccessory = 
      (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
    
    if(usbAccessory!=null && usbAccessory.equals(myUsbAccessory)){
     closeUsbAccessory();
    }
   }
  }
 };
 
 private BroadcastReceiver myUsbPermissionReceiver = new BroadcastReceiver(){

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

    synchronized(this){
     
     UsbAccessory usbAccessory = 
       (UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);
     
     if(intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)){
      OpenUsbAccessory(usbAccessory);
     }else{
      finish();
     }
    }
   }
  }
  
 };
 
 private void OpenUsbAccessory(UsbAccessory acc){
  myAdkParcelFileDescriptor = myUsbManager.openAccessory(acc);
  if(myAdkParcelFileDescriptor != null){
   
   myUsbAccessory = acc;
   FileDescriptor fileDescriptor = myAdkParcelFileDescriptor.getFileDescriptor();
   myAdkInputStream = new FileInputStream(fileDescriptor);
   myAdkOutputStream = new FileOutputStream(fileDescriptor);
   
   Thread thread = new Thread(runnableReadAdk);
   thread.start();
  }
 }
 
 private void closeUsbAccessory(){
  
  if(myAdkParcelFileDescriptor != null){
   try {
    myAdkParcelFileDescriptor.close();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
  
  myAdkParcelFileDescriptor = null;
  myUsbAccessory = null;
 }
}


MainActivity.java
package com.example.androidadkcommunication;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AbstractAdkActivity {

 TextView textIn;
 EditText editOut;
 Button buttonSend;
 
 @Override
 protected void doOnCreate(Bundle savedInstanceState) {
  setContentView(R.layout.activity_main);
  textIn = (TextView)findViewById(R.id.panelin);
  editOut = (EditText)findViewById(R.id.textout);
  buttonSend = (Button)findViewById(R.id.send);
  buttonSend.setOnClickListener(buttonSendOnClickListener);
  
 }
 
 OnClickListener buttonSendOnClickListener =
   new OnClickListener(){

    @Override
    public void onClick(View arg0) {
     WriteAdk(editOut.getText().toString());
     editOut.setText("");
    }
 };

 @Override
 protected void doAdkRead_inBackGroundThread(int length, byte[] bfr) {

  final String bfrIn = new String(bfr);
  
  runOnUiThread(new Runnable(){

   @Override
   public void run() {
    textIn.setText(bfrIn);
   }});
 }

}


Download Project files.

Look for help: write failed: ENODEV (No such device)

No comments:

Post a Comment