Thursday, 19 July 2012

Arduino ADK Board: Blink an LED With Your Phone, Minimum Code Required

Arduino ADK Board: Blink an LED With Your Phone, Minimum Code Required

by Miguel on December 31, 2011
I recently bought an Arduino ADK board, after downloading the sample code I was overwhelmed with the amount of C and Java code I saw. Furthermore the sample code requires that you have all these sensors that are sold separately on top of the already expensive board, and this is supposed to be a beginners board?
But enough with the rant, I’ve managed to trimmed the C and JAVA down to what is only necessary to blink the built in LED in the Arduino, the full code and explanation is here, please spread it around.

The App’s Interface

The Android app consists of a toggle button which we’ll use to toggle the state, on or off, of the LED. In Android user interfaces are called layouts, so let’s make a layout with a toggle button.
android toggle button
Android app interface as seen in phone
The ToggleButton xml tag has several properties including dimensions (width and height), position, text size and the ID and onClick attributes. The ID attribute is used to identify inputs (buttons, check boxes etc) in our Java code, the onClick attribute is the function which will executed upon a click.
File: layout/main.xml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout android:layout_width="fill_parent"
  3. android:id="@+id/relativeLayout1"
  4. android:layout_height="fill_parent"
  5. android:layout_weight="0.72" xmlns:android="http://schemas.android.com/apk/res/android">
  6. <ToggleButton
  7. android:text="ToggleButton"
  8. android:id="@+id/toggleButtonLED"
  9. android:layout_width="500px"
  10. android:layout_height="200px"
  11. android:layout_centerVertical="true"
  12. android:layout_centerHorizontal="true"
  13. android:textSize="50px"
  14. android:onClick="blinkLED"></ToggleButton>
  15. </RelativeLayout>
In the code above, our button’s ID is toggleButtonLED and the function to execute when it’s clicked is blinkLED.

Asking For Permission

Whenever you download an app, if you don’t just click OK on everything without reading, you’ll notice that it lists some permissions that it requires from the device. All these permissions are listed in the Android manifest file ("manifest"? LOL sounds like a peace treaty doesn’t it?), we need to list our USB permissions in this file.
File: AndroidManifest.xml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.yoursite.arduinoblinkled" android:versionCode="1"
  4. android:versionName="1.0">
  5. <uses-sdk android:minSdkVersion="13" />
  6.  
  7. <application android:icon="@drawable/icon" android:label="@string/app_name">
  8. <activity android:name=".ArduinoBlinkLEDActivity"
  9. android:label="@string/app_name">
  10. <intent-filter>
  11. <action android:name="android.intent.action.MAIN" />
  12. <category android:name="android.intent.category.LAUNCHER" />
  13. </intent-filter>
  14. <intent-filter>
  15. <action android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED" />
  16. </intent-filter>
  17. <meta-data android:name="android.hardware.usb.action.USB_ACCESSORY_ATTACHED"
  18. android:resource="@xml/accessory_filter" />
  19. </activity>
  20. <uses-library android:name="com.android.future.usb.accessory"></uses-library>
  21.  
  22. </application>
  23. </manifest>
Be sure to change the minSdkVersion to the Android SDK version your project is using.

How To Route Your USB Device To The Correct Application

android message of new usb device connection
The message you'll get when you connect your board to the Android device

Whenever you connect your board the Android device (phone or table) will need to know which app the board uses, we do that with this file.
File: accessory_filter.xml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <usb-accessory manufacturer="Manufacturer" model="Model" version="1.0" />
  4. </resources>
You may change the values in the attributes but they will have to same as in the Arduino file.

How To Handle The Clicks, Send Data To The Board

The following code is part of the ArduinoBlinkLED.java file, don’t worry about where it goes for now, I will tell you that later, for now just understand the following explanations.
To make our button be recognized by Java we need to store it in an object. So we declared our object as a ToggleButton object:
  1. private ToggleButton buttonLED;
Then we store our button in the buttonLED object:
  1. // toggleButtonLED is the name we used in the layout/main.xml code above.
  2. buttonLED = (ToggleButton) findViewById(R.id.toggleButtonLED);
We also need to load the layout into our app.
  1. // main comes from our interface's file name: main.xml
  2. setContentView(R.layout.main);
To handle the button clicks we’ll need to make the function blinkLED, just as we promised in the layout/main.xml code above. This is the function’s code:
  1. public void blinkLED(View v){
  2.  
  3. byte[] buffer = new byte[1];
  4. if(buttonLED.isChecked())
  5. buffer[0]=(byte)0; // button says on, light is off
  6. else
  7. buffer[0]=(byte)1; // button says off, light is on
  8. if (mOutputStream != null) {
  9. try {
  10. mOutputStream.write(buffer);
  11. } catch (IOException e) {
  12. Log.e(TAG, "write failed", e);
  13. }
  14. }
  15. }
What we are doing here is we are making a byte array which will hold the value 0 if the button is checked and the value 1 if it’s not checked, read the comments in the code. The byte is sent to the Arduino ADK board by the write function.
We’ll continue in the same file on the next section.

Android Arduino Communication

The code that handles USB communication is standard code you’ll need for all your apps, you can either not worry about it or simply check out each function and by the variable names am confident you’ll understand what it’s doing, also in the code to handle clicks is included here. Am sorry I can’t explain each piecebut as you’ll see it could take a while, but the important part is what I explained above.
We only need ONE java file, not 100′s like the "demo" version and here it is.
File: ArduinoBlinkLED.java
  1. package com.yoursite.arduinoblinkled;
  2.  
  3. import java.io.FileDescriptor;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7.  
  8. import android.app.Activity;
  9. import android.app.PendingIntent;
  10. import android.content.BroadcastReceiver;
  11. import android.content.Context;
  12. import android.content.Intent;
  13. import android.content.IntentFilter;
  14. import android.os.Bundle;
  15. import android.os.ParcelFileDescriptor;
  16. import android.util.Log;
  17. import android.view.View;
  18. import android.widget.ToggleButton;
  19.  
  20. import com.android.future.usb.UsbAccessory;
  21. import com.android.future.usb.UsbManager;
  22.  
  23. public class ArduinoBlinkLEDActivity extends Activity {
  24.  
  25. // TAG is used to debug in Android logcat console
  26. private static final String TAG = "ArduinoAccessory";
  27.  
  28. private static final String ACTION_USB_PERMISSION = "com.google.android.DemoKit.action.USB_PERMISSION";
  29.  
  30. private UsbManager mUsbManager;
  31. private PendingIntent mPermissionIntent;
  32. private boolean mPermissionRequestPending;
  33. private ToggleButton buttonLED;
  34.  
  35. UsbAccessory mAccessory;
  36. ParcelFileDescriptor mFileDescriptor;
  37. FileInputStream mInputStream;
  38. FileOutputStream mOutputStream;
  39.  
  40. private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
  41. @Override
  42. public void onReceive(Context context, Intent intent) {
  43. String action = intent.getAction();
  44. if (ACTION_USB_PERMISSION.equals(action)) {
  45. synchronized (this) {
  46. UsbAccessory accessory = UsbManager.getAccessory(intent);
  47. if (intent.getBooleanExtra(
  48. UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
  49. openAccessory(accessory);
  50. } else {
  51. Log.d(TAG, "permission denied for accessory "
  52. + accessory);
  53. }
  54. mPermissionRequestPending = false;
  55. }
  56. } else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
  57. UsbAccessory accessory = UsbManager.getAccessory(intent);
  58. if (accessory != null && accessory.equals(mAccessory)) {
  59. closeAccessory();
  60. }
  61. }
  62. }
  63. };
  64.  
  65.  
  66. @Override
  67. public void onCreate(Bundle savedInstanceState) {
  68. super.onCreate(savedInstanceState);
  69.  
  70. mUsbManager = UsbManager.getInstance(this);
  71. mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
  72. IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
  73. filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
  74. registerReceiver(mUsbReceiver, filter);
  75.  
  76. if (getLastNonConfigurationInstance() != null) {
  77. mAccessory = (UsbAccessory) getLastNonConfigurationInstance();
  78. openAccessory(mAccessory);
  79. }
  80.  
  81. setContentView(R.layout.main);
  82. buttonLED = (ToggleButton) findViewById(R.id.toggleButtonLED);
  83. }
  84.  
  85. @Override
  86. public Object onRetainNonConfigurationInstance() {
  87. if (mAccessory != null) {
  88. return mAccessory;
  89. } else {
  90. return super.onRetainNonConfigurationInstance();
  91. }
  92. }
  93.  
  94. @Override
  95. public void onResume() {
  96. super.onResume();
  97.  
  98. if (mInputStream != null && mOutputStream != null) {
  99. return;
  100. }
  101.  
  102. UsbAccessory[] accessories = mUsbManager.getAccessoryList();
  103. UsbAccessory accessory = (accessories == null ? null : accessories[0]);
  104. if (accessory != null) {
  105. if (mUsbManager.hasPermission(accessory)) {
  106. openAccessory(accessory);
  107. } else {
  108. synchronized (mUsbReceiver) {
  109. if (!mPermissionRequestPending) {
  110. mUsbManager.requestPermission(accessory,mPermissionIntent);
  111. mPermissionRequestPending = true;
  112. }
  113. }
  114. }
  115. } else {
  116. Log.d(TAG, "mAccessory is null");
  117. }
  118. }
  119.  
  120. @Override
  121. public void onPause() {
  122. super.onPause();
  123. closeAccessory();
  124. }
  125.  
  126. @Override
  127. public void onDestroy() {
  128. unregisterReceiver(mUsbReceiver);
  129. super.onDestroy();
  130. }
  131.  
  132. private void openAccessory(UsbAccessory accessory) {
  133. mFileDescriptor = mUsbManager.openAccessory(accessory);
  134. if (mFileDescriptor != null) {
  135. mAccessory = accessory;
  136. FileDescriptor fd = mFileDescriptor.getFileDescriptor();
  137. mInputStream = new FileInputStream(fd);
  138. mOutputStream = new FileOutputStream(fd);
  139. Log.d(TAG, "accessory opened");
  140. } else {
  141. Log.d(TAG, "accessory open fail");
  142. }
  143. }
  144.  
  145.  
  146. private void closeAccessory() {
  147. try {
  148. if (mFileDescriptor != null) {
  149. mFileDescriptor.close();
  150. }
  151. } catch (IOException e) {
  152. } finally {
  153. mFileDescriptor = null;
  154. mAccessory = null;
  155. }
  156. }
  157.  
  158. public void blinkLED(View v){
  159.  
  160. byte[] buffer = new byte[1];
  161.  
  162. if(buttonLED.isChecked())
  163. buffer[0]=(byte)0; // button says on, light is off
  164. else
  165. buffer[0]=(byte)1; // button says off, light is on
  166.  
  167. if (mOutputStream != null) {
  168. try {
  169. mOutputStream.write(buffer);
  170. } catch (IOException e) {
  171. Log.e(TAG, "write failed", e);
  172. }
  173. }
  174. }
  175.  
  176. }

How To Receive Data From The Android Device

Here comes the easy part. This is the only Arduino code you need. Notice how the manufacturer, model and version values matches that of our accessory_filter.xml file, if any of these change your board will not know which app to load.
  1. #include <Max3421e.h>
  2. #include <Usb.h>
  3. #include <AndroidAccessory.h>
  4. #define LED_PIN 13
  5. AndroidAccessory acc("Manufacturer",
  6. "Model",
  7. "Description",
  8. "1.0",
  9. "http://yoursite.com",
  10. "0000000012345678");
  11. void setup()
  12. {
  13. // set communiation speed
  14. Serial.begin(115200);
  15. pinMode(LED_PIN, OUTPUT);
  16. acc.powerOn();
  17. }
  18.  
  19. void loop()
  20. {
  21. byte msg[0];
  22. if (acc.isConnected()) {
  23. int len = acc.read(msg, sizeof(msg), 1); // read data into msg variable
  24. if (len > 0) {
  25. if (msg[0] == 1) // compare received data
  26. digitalWrite(LED_PIN,HIGH); // turn on light
  27. else
  28. digitalWrite(LED_PIN,LOW); // turn off light
  29. }
  30. }
  31. else
  32. digitalWrite(LED_PIN , LOW); // turn off light
  33. }
  34.  

File Locations

Just in case you don’t know where the code I gave you goes:
location of the files
the location of the files as seen in eclipse



 

3 comments:

  1. Thanks It was a great HelpfulCode

    ReplyDelete
  2. Love it! Thanks!
    But to make it work today:
    The imports for USB must be changed from com.android.future.usb.... to android.hardware.usb....

    In line 128 and 139 change:
    UsbAccessory accessory = UsbManager.getAccessory(intent);
    to:
    UsbAccessory accessory =(UsbAccessory)intent.getParcelableExtra(UsbManager.EXTRA_ACCESSORY);


    Line 152 must go from:
    mUsbManager = UsbManager.getInstance(this);
    to:
    mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

    Now I just have to wait for my USB host board to come in so that I can play with some stuff....

    http://emt-scientist.blogspot.nl/2011/05/adk-compiled-for-android-31.html

    Or atleast I had to do that in order to get everything to work.

    Thanks again though!
    XOXO

    ReplyDelete
  3. Do you have this code on github?

    ReplyDelete