Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Monday, April 11, 2016

Android BluetoothChat connect to Arduino Uno + HC-05

Last example show "Android BluetoothChat example link with HC-05 Bluetooth", to connect to PC via FTDI adapter. Here is another example - Arduino UNO + HC-05 to echo received data back to the sender.

For my on-hand HC-05 sample, it set as slave role and 9600, 0, 0, PIN="1234" by default. So it can be used in this example without any extra setting.


Connection between UNO and HC-05
HC-05 Rx - Uno Tx (1)
HC-05 Tx - Uno Rx (0)
HC-05 GND - Uno GND
HC-05 VCC - Uno 5V
(My HC-05 marked "Power: 3.6V-6V", refer here, make sure your HC-05 can work on 5V.)

Uno_Serial_echo.ino
/*
Arduino Uno + HC-05 (Bluetooth) - echo bluetooth data

Serial (Tx/Rx) communicate to HC-05
HC-05 Rx - Uno Tx (1)
HC-05 Tx - Uno Rx (0)
HC-05 GND - Uno GND
HC-05 VCC - Uno 5V

*/

void setup()
{
  delay(1000);
  Serial.begin(9600);
}

void loop()
{
  while(Serial.available())
  {
    char data = Serial.read();
    Serial.write(data);
  }
}

This video show how Android BluetoothChat example link with Arduino UNO + HC-05. For the Android BluetoothChat example, refer last post.


Related:
Connect Arduino Due with HC-06 (Bluetooth Module)





Thursday, April 7, 2016

Android BluetoothChat example link with HC-05 Bluetooth

This example show to import and modify Android BluetoothChat example, to link with low-cost Bluetooth HC-05.

reference:
First test HC-05 Bluetooth Module
AT Command mode of HC-05

We need a FTDI USB-to-Serial adapter to connect PC/USB and HC-05 Bluetooth, and use Arduino IDE's Serial Monitor as terminal, to talk with Android running modified BluetoothChat example.


This video show how to import BluetoothChat example in Android Studio, and edit BluetoothChatService.java to change MY_UUID_SECURE to UUID.fromString("00001101-0000-1000-8000-00805F9B34FB").

~ reference http://developer.android.com/reference/android/bluetooth/BluetoothDevice.htmlIf you are connecting to a Bluetooth serial board then try using the well-known SPP UUID 00001101-0000-1000-8000-00805F9B34FB.


This video show how it run on Android device, and talk to PC running Arduino IDE's Serial Monitor, via FTDI + HC-05.

In my on-hand HC-05 sample, it set as slave role and 9600, 0, 0, PIN="1234" by default, I have not change any setting.


Cross-post with Android-er

Next:
Android BluetoothChat connect to Arduino Uno + HC-05

Thursday, October 15, 2015

Android control Arduino Due LED, using ADK (Accessory Development Kit)

I have old posts of "Android code sending command to Arduino Due to turn LED On/Off (Android side)" and "Control Arduino Due LED from Android using ADK (Arduino Due side)" to show a simple control from Android to Arduino Due using ADK (Accessory Development Kit), at 2013. At both Android and Arduino development tools updated, I re-visit the example code again.



Arduino Due Side:

In current Arduino IDE 1.6.5, both Arduino Due and ADK library are not include by default, so you have to:
- Install Arduino Due to Arduino IDE
- Install USBHost library to Arduino IDE

DurAdkLed.ino (same as before)
#include "variant.h"
#include <stdio.h>
#include <adk.h>

// Accessory descriptor. It's how Arduino identifies itself to Android.
char applicationName[] = "HelloADKLED"; // the app on your phone
char accessoryName[] = "Arduino Due"; // your Arduino board
char companyName[] = "Arduino-er";
 
// Make up anything you want for these
char versionNumber[] = "0.1";
char serialNumber[] = "1";
char url[] = "https://sites.google.com/site/arduinosite/exercise/androidadkled/AndroidADKLED_0.1.apk";
 
USBHost Usb;
ADK adk(&Usb, companyName, applicationName, accessoryName,versionNumber,url,serialNumber);
 
// Pin 13 has an LED connected on most Arduino boards.
int led = 13;
 
void setup() {
    Serial.begin(9600);
    cpu_irq_enable();
   
    pinMode(led, OUTPUT);
    //Indicate start of program
    digitalWrite(led, LOW);
    delay(2000);
    digitalWrite(led, HIGH);
    for(int i = 0; i <= 2; i++){
        digitalWrite(led, HIGH);
        delay(250);
        digitalWrite(led, LOW);
        delay(250);
    }
}
 
#define RCVSIZE 128
 
void loop() {
   
    char helloworld[] = "Hello World!\r\n";
   
    uint8_t buf[RCVSIZE];
    uint32_t nbread = 0;
   
    Usb.Task();
     
    if (adk.isReady()){
      
        adk.read(&nbread, RCVSIZE, buf);
        if (nbread > 0){
            adk.write(nbread, buf);
            
            //Convert nbread to String
            String s = "";
            for (uint32_t i = 0; i < nbread; ++i) {
              s += (char)buf[i];
            }
            
            if(s == "LEDON"){
              digitalWrite(led, HIGH);
            }else if(s == "LEDOFF"){
              digitalWrite(led, LOW);
            }
        }
         
    }
     
}


Android Side:

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.blogspot.android_er.androidadkled" >

    <uses-feature android:name="android.hardware.usb.accessory"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <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>


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

layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:padding="16dp"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://arduino-er.blogspot.com/"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <RadioGroup
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <RadioButton
            android:id="@+id/LedOn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LED On" />
        <RadioButton
            android:id="@+id/LedOff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LED Off" />
    </RadioGroup>
</LinearLayout>


AbstractAdkActivity.java
package com.blogspot.android_er.androidadkled;

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;
import android.support.v7.app.AppCompatActivity;

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

public abstract  class AbstractAdkActivity extends AppCompatActivity {

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

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

    @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;
            byte[] buffer = new byte[255];

            while(numberOfByteRead >= 0){

                try {
                    numberOfByteRead = myAdkInputStream.read(buffer, 0, buffer.length);
                    final StringBuilder stringBuilder = new StringBuilder();
                    for(int i=0; i<numberOfByteRead; i++){
                        stringBuilder.append((char)buffer[i]);
                    }

                    runOnUiThread(new Runnable(){

                        @Override
                        public void run() {
                            doAdkRead(stringBuilder.toString());
                        }});


                } 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.blogspot.android_er.androidadkled;

import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AbstractAdkActivity  {

    TextView textIn;
    RadioButton ledOn, ledOff;

    @Override
    protected void doOnCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        textIn = (TextView)findViewById(R.id.textin);
        ledOn = (RadioButton)findViewById(R.id.LedOn);
        ledOff = (RadioButton)findViewById(R.id.LedOff);

        ledOn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                if(isChecked){
                    WriteAdk("LEDON");
                    Toast.makeText(getApplicationContext(),
                            "LEDON", Toast.LENGTH_LONG).show();
                }
            }});

        ledOff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                if(isChecked){
                    WriteAdk("LEDOFF");
                    Toast.makeText(getApplicationContext(),
                            "LEDOFF", Toast.LENGTH_SHORT).show();
                }
            }});

    }

    @Override
    protected void doAdkRead(String stringIn) {
        textIn.setText(stringIn);
    }
}



Tuesday, September 2, 2014

Communication between Android and Arduino Uno, in USB Host Mode

It's a example to implement communication between Android and Arduino Uno. Here Android is running in USB Host Mode. String received in Arduino Uno is displayed on 2x16 LCD Module.

Android side, refer to the post "Send data from Android to Arduino Uno, in USB Host Mode" of my Android blog.

Arduino Uno side, refer to last post "Read from Arduino Serial port, and write to 2x16 LCD".


Friday, July 11, 2014

Beginning NFC with PhoneGap and Arduino - O'Reilly Webcast



Beginning NFC with PhoneGap and Arduino - O'Reilly Webcast

Originally recorded April 29, 2014. Don Coleman, Tom Igoe, and Brian Jepson (authors of Beginning NFC ) will introduce you to Near Field Communication using Android phones, Arduino, and NFC readers for computers and Arduino. Learn how information on NFC tags is stored and retrieved, how to write applications on Arduino and Android to read and write tags, and how to integrate NFC into larger projects.

Two demos in this session will feature :
  • Reading a tag with an Android PhoneGap application
  • Writing to a tag from Arduino
  • And when both are done, we'll be able to show you how an Android device can read the tag you wrote from Arduino and take an action based on the data you stored.

Monday, March 31, 2014

Send string command from Android to Arduino in USB Host Mode

This is a example in my another blog show how Android send command to Arduino in USB Host mode. When user toggle the LED by clicking on the button, or change the screen color by slideing the bars, the commands will be add in a command queue, and then send to Arduino in background.

The code in Arduino Esplora is same as the previous example of Node.js + Arduino, running on PC.


Thursday, February 20, 2014

Send data from Android to Arduino Esplora in USB Host Mode

It's a exercise in my another blog "Android-er: Send Hello to Arduino from Android in USB Host Mode". The post show how to detect attached Arduino Esplora board on Android, run in USB Host Mode, and send data to it.

Monday, June 17, 2013

Import and setup Android ADK terminal emulator, to work with Arduino ADKTerminalTest example

Last post introduced "Modified ADKTerminalTest example of Arduino 1.5.2", it work with "http://labs.arduino.cc/uploads/ADK/ArduinoTerminal/ThibaultTerminal_ICS_0001.apk" in default. Alternatively, Circuits@Home provide a project "Android ADK terminal emulator for Arduino" with source code, it can work with the modified ADKTerminalTest. This post descript how to import and setup in Eclipse of Android Developer Tools.

Prepare:

- It's assumed you have Android SDK installed on your PC.

- Download and unzip source code of ArduinoTerminalSrc.zip from "Android ADK terminal emulator for Arduino page", it can also be download here directly.

- Make sure Android 2.3.3 (API 10) and associated Google APIs are installed in your Android Developer Tools. In Eclipse, select Window in menu bar, -> Android SDK Manager.


Import downloaded ArduinoTerminalSrc:

- Click File -> Import...


-  Select "Existing Android Code into Workspace" under Android section.



- Browse to select downloaded and unziped folder.


- Optionally check "Copy projects into workspace" and click Finish.


- After a moment of auto-build, many error of something like "The import com.android.future cannot be resolved" will be reported.


- Right click your project - > Properties.


- Select Target Google APIs of Platform 2.3.3, and click OK.


- After finished and re-built, you can download it to your Android device. It can work with the modified ADKTerminalTest.

remark:
- Tested on Nexus One with Android 2.3.6. But not work on HTC One X with Android 4.1.1, dur to issues of Theme!


Tuesday, June 4, 2013

write failed: ENODEV (No such device)



In this previous exercise "Android code for Communication between Android and Arduino Due", it work as expected after plug in Android device into Arduino Due board.



The problem is:

Once I switch out and back the app, and perform onResume()... The app can get fileDescriptor, myAdkInputStream and myAdkOutputStream. But when it try to write to myAdkOutputStream in WriteAdk(String text) method, IOException of "write failed: ENODEV (No such device)" thrown!

Anybody can advise?

Monday, May 27, 2013

Processing + Android

Processing is an open source programming language and environment for people who want to create images, animations, and interactions. Initially developed to serve as a software sketchbook and to teach fundamentals of computer programming within a visual context, Processing also has evolved into a tool for generating finished professional work. Today, there are tens of thousands of students, artists, designers, researchers, and hobbyists who use Processing for learning, prototyping, and production.
  • Free to download and open source
  • Interactive programs using 2D, 3D or PDF output
  • OpenGL integration for accelerated 3D
  • For GNU/Linux, Mac OS X, and Windows
  • Projects run online or as double-clickable applications
  • Over 100 libraries extend the software into sound, video, computer vision, and more...
  • Well documented, with many books available

Processing for Android project is aim to make it foolishly easy to create Android apps using the Processing API. Once you have Processing on your machine (and the Android developer tools), you can simply write a line of code, hit Run (Ctrl-R or Cmd-R), and have your sketch show up in the emulator as a working Android app. Select Run on Device (Ctrl-Shift-R or Cmd-Shift-R) to have it run on an Android device that you have plugged into your machine. That's good stuff!

Read Tutorial to develop Android App with Processing version 2.0+.



It's cross-post with Android-er.

Sunday, March 31, 2013

Android code sending command to Arduino Due to turn LED On/Off

It's the coding in Android side to send command to Arduino Due to control LED On/Off.


Modify AndroidManifest.xml to add <uses-feature> of "android.hardware.usb.accessory", <intent-filter> of "android.hardware.usb.action.USB_ACCESSORY_ATTACHED", and <meta-data> of resource="@xml/myfilter".
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidadkled"
    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" >
        <activity
            android:name="com.example.androidadkled.MainActivity"
            android:label="@string/app_name" >
            <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>


Create file /res/xml/myfilter.xml
<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <usb-accessory
        manufacturer="Arduino-er"
        model="HelloADKLED"
        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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Arduino LED Control" />
    <TextView
        android:id="@+id/textin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <RadioGroup
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <RadioButton
            android:id="@+id/LedOn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LED On" />
        <RadioButton
            android:id="@+id/LedOff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="LED Off" />
    </RadioGroup>

</LinearLayout>


Create a abstract class AbstractAdkActivity.java to extend Activity, implement the function of ADK; such that we can easy re-use it in furture and reduce the ADK related job in MainActivity.java.
/*
 * abstract class for Activities have to read ADK
 * for android:minSdkVersion="12"
 * 
 */

package com.example.androidadkled;

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); 
 
 @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();
   } 
  }
 }
 
 @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;
   byte[] buffer = new byte[255];
   
   while(numberOfByteRead >= 0){
    
    try {
     numberOfByteRead = myAdkInputStream.read(buffer, 0, buffer.length);
     final StringBuilder stringBuilder = new StringBuilder();
     for(int i=0; i<numberOfByteRead; i++){
      stringBuilder.append((char)buffer[i]);
     }
     
     runOnUiThread(new Runnable(){

      @Override
      public void run() {
       doAdkRead(stringBuilder.toString());
      }});
     
     
    } 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;
 }
}


Modify MainActivity.java to extend AbstractAdkActivity, and extend Activity in-turn. With AbstractAdkActivity handle most of the ADK related job, we only have to override the methods doOnCreate()(called in onCreate() method) and doAdkRead()(called after command read from ADK). To send command to ADK, call WriteAdk() method.
package com.example.androidadkled;

import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AbstractAdkActivity {
 
 TextView textIn;
 RadioButton ledOn, ledOff;

 @Override
 protected void doOnCreate(Bundle savedInstanceState) {
  setContentView(R.layout.activity_main);
  textIn = (TextView)findViewById(R.id.textin);
  ledOn = (RadioButton)findViewById(R.id.LedOn);
  ledOff = (RadioButton)findViewById(R.id.LedOff);
  
  ledOn.setOnCheckedChangeListener(new OnCheckedChangeListener(){

   @Override
   public void onCheckedChanged(CompoundButton buttonView,
     boolean isChecked) {
    if(isChecked){
     WriteAdk("LEDON");
     Toast.makeText(getApplicationContext(), 
       "LEDON", Toast.LENGTH_LONG).show();
    }
   }});
  
  ledOff.setOnCheckedChangeListener(new OnCheckedChangeListener(){

   @Override
   public void onCheckedChanged(CompoundButton buttonView,
     boolean isChecked) {
    if(isChecked){
     WriteAdk("LEDOFF");
     Toast.makeText(getApplicationContext(), 
       "LEDOFF", Toast.LENGTH_SHORT).show();
    }
   }});

 }

 @Override
 protected void doAdkRead(String stringIn) {
  textIn.setText(stringIn);
 }

}


download filesDownload the files.

Refer the another post for the code in Arduino Due side.


Updated@2015-10-15Android control Arduino Due LED, using ADK (Accessory Development Kit)

Friday, February 15, 2013

Professional Android Open Accessory Programming with Arduino

Professional Android Open Accessory Programming with Arduino


Learn how to control your home or car from your Android smartphone - air conditioning, lights, entertainment systems, and more!
Android Open Accessory is a new, simple, and secure protocol for connecting any microcontroller-empowered device to an Android smartphone or tablet. This Wrox guide shows Android programmers how to use AOA with Arduino, the microcontroller platform, to control such systems as lighting, air conditioning, and entertainment systems from Android devices. Furthermore, it teaches the circuit-building skills needed to create games and practical products that also take advantage of Android technology.
  • Introduces Android Open Accessory and shows how to set up the hardware and development environment
  • Explains how to code both Android and Arduino elements of an accessory
  • Features four complete projects developers can build using various sensors and indicators/actuators, including source code
  • Gives Android developers the tools to create powerful, sophisticated projects
Professional Android Open Accessory with Android ADK and Arduino opens exciting new opportunities for Android developers.

Arduino MEGA ADK R3 for Android

Arduino MEGA ADK R3 for Android

  • The Arduino ADK is a microcontroller board based on the ATmega2560
  • It has a USB host interface to connect with Android based phones, based on the MAX3421e IC
  • For information on using the board with the Android OS, see Google's ADK documentation.
  • Android Development Board
  • R3 board

Thursday, February 14, 2013

About Android Open Accessory

Android Open Accessory support allows external USB hardware (an Android USB accessory) to interact with an Android-powered device in a special accessory mode. When an Android-powered powered device is in accessory mode, the connected accessory acts as the USB host (powers the bus and enumerates devices) and the Android-powered device acts in the USB accessory role. Android USB accessories are specifically designed to attach to Android-powered devices and adhere to the Android Open Accessory Protocol, that allows them to detect Android-powered devices that support accessory mode. Accessories must also provide 500mA at 5V for charging power. Many previously released Android-powered devices are only capable of acting as a USB device and cannot initiate connections with external USB devices. Android Open Accessory support overcomes this limitation and allows you to build accessories that can interact with an assortment of Android-powered devices by allowing the accessory to initiate the connection.

Note: Accessory mode is ultimately dependent on the device's hardware and not all devices support accessory mode. Devices that support accessory mode can be filtered using a element in your corresponding application's Android manifest. For more information, see the USB Accessory developer guide.

Android Open Accessory support is included in Android 3.1 (API Level 12) and higher, and supported through an Add-On Library in Android 2.3.4 (API Level 10) and higher.