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

by Miguel on December 31, 2011

in Android,Arduino

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

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="fill_parent"
	android:id="@+id/relativeLayout1" 
	android:layout_height="fill_parent"
	android:layout_weight="0.72" xmlns:android="http://schemas.android.com/apk/res/android">
	<ToggleButton 
	android:text="ToggleButton" 
	android:id="@+id/toggleButtonLED" 
	android:layout_width="500px" 
	android:layout_height="200px" 
	android:layout_centerVertical="true" 
	android:layout_centerHorizontal="true"
	android:textSize="50px"
	android:onClick="blinkLED"></ToggleButton>
</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

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.yoursite.arduinoblinkled" android:versionCode="1"
	android:versionName="1.0">
	<uses-sdk android:minSdkVersion="13" />

	<application android:icon="@drawable/icon" android:label="@string/app_name">
		<activity android:name=".ArduinoBlinkLEDActivity"
			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/accessory_filter" />
		</activity>
		
		<uses-library android:name="com.android.future.usb.accessory"></uses-library>

	</application>
</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

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <usb-accessory manufacturer="Manufacturer" model="Model" version="1.0" />
</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:

private ToggleButton buttonLED;

Then we store our button in the buttonLED object:

// toggleButtonLED is the name we used in the layout/main.xml code above.
buttonLED = (ToggleButton) findViewById(R.id.toggleButtonLED);

We also need to load the layout into our app.

// main comes from our interface's file name: main.xml
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:

public void blinkLED(View v){

	byte[] buffer = new byte[1];
	if(buttonLED.isChecked())
		buffer[0]=(byte)0; // button says on, light is off
	else
		buffer[0]=(byte)1; // button says off, light is on
	if (mOutputStream != null) {
		try {
			mOutputStream.write(buffer);
		} catch (IOException e) {
			Log.e(TAG, "write failed", e);
		}
	}
}

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

package com.yoursite.arduinoblinkled;

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.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.view.View;
import android.widget.ToggleButton;

import com.android.future.usb.UsbAccessory;
import com.android.future.usb.UsbManager;

public class ArduinoBlinkLEDActivity extends Activity {

	// TAG is used to debug in Android logcat console
	private static final String TAG = "ArduinoAccessory";

	private static final String ACTION_USB_PERMISSION = "com.google.android.DemoKit.action.USB_PERMISSION";

	private UsbManager mUsbManager;
	private PendingIntent mPermissionIntent;
	private boolean mPermissionRequestPending;
	private ToggleButton buttonLED;

	UsbAccessory mAccessory;
	ParcelFileDescriptor mFileDescriptor;
	FileInputStream mInputStream;
	FileOutputStream mOutputStream;

	private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (ACTION_USB_PERMISSION.equals(action)) {
				synchronized (this) {
					UsbAccessory accessory = UsbManager.getAccessory(intent);
					if (intent.getBooleanExtra(
							UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
						openAccessory(accessory);
					} else {
						Log.d(TAG, "permission denied for accessory "
								+ accessory);
					}
					mPermissionRequestPending = false;
				}
			} else if (UsbManager.ACTION_USB_ACCESSORY_DETACHED.equals(action)) {
				UsbAccessory accessory = UsbManager.getAccessory(intent);
				if (accessory != null && accessory.equals(mAccessory)) {
					closeAccessory();
				}
			}
		}
	};


	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mUsbManager = UsbManager.getInstance(this);
		mPermissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
		IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
		filter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
		registerReceiver(mUsbReceiver, filter);

		if (getLastNonConfigurationInstance() != null) {
			mAccessory = (UsbAccessory) getLastNonConfigurationInstance();
			openAccessory(mAccessory);
		}

		setContentView(R.layout.main);
		buttonLED = (ToggleButton) findViewById(R.id.toggleButtonLED);
		
	}

	@Override
	public Object onRetainNonConfigurationInstance() {
		if (mAccessory != null) {
			return mAccessory;
		} else {
			return super.onRetainNonConfigurationInstance();
		}
	}

	@Override
	public void onResume() {
		super.onResume();

		if (mInputStream != null && mOutputStream != null) {
			return;
		}

		UsbAccessory[] accessories = mUsbManager.getAccessoryList();
		UsbAccessory accessory = (accessories == null ? null : accessories[0]);
		if (accessory != null) {
			if (mUsbManager.hasPermission(accessory)) {
				openAccessory(accessory);
			} else {
				synchronized (mUsbReceiver) {
					if (!mPermissionRequestPending) {
						mUsbManager.requestPermission(accessory,mPermissionIntent);
						mPermissionRequestPending = true;
					}
				}
			}
		} else {
			Log.d(TAG, "mAccessory is null");
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		closeAccessory();
	}

	@Override
	public void onDestroy() {
		unregisterReceiver(mUsbReceiver);
		super.onDestroy();
	}

	private void openAccessory(UsbAccessory accessory) {
		mFileDescriptor = mUsbManager.openAccessory(accessory);
		if (mFileDescriptor != null) {
			mAccessory = accessory;
			FileDescriptor fd = mFileDescriptor.getFileDescriptor();
			mInputStream = new FileInputStream(fd);
			mOutputStream = new FileOutputStream(fd);
			Log.d(TAG, "accessory opened");
		} else {
			Log.d(TAG, "accessory open fail");
		}
	}


	private void closeAccessory() {
		try {
			if (mFileDescriptor != null) {
				mFileDescriptor.close();
			}
		} catch (IOException e) {
		} finally {
			mFileDescriptor = null;
			mAccessory = null;
		}
	}

	public void blinkLED(View v){

		byte[] buffer = new byte[1];

		if(buttonLED.isChecked())
			buffer[0]=(byte)0; // button says on, light is off
		else
			buffer[0]=(byte)1; // button says off, light is on

		if (mOutputStream != null) {
			try {
				mOutputStream.write(buffer);
			} catch (IOException e) {
				Log.e(TAG, "write failed", e);
			}
		}
	}

}

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.

#include <Max3421e.h>
#include <Usb.h>
#include <AndroidAccessory.h>
#define  LED_PIN  13
AndroidAccessory acc("Manufacturer",
		"Model",
		"Description",
		"1.0",
		"http://yoursite.com",
                "0000000012345678");
void setup()
{
  // set communiation speed
  Serial.begin(115200);
  pinMode(LED_PIN, OUTPUT);
  acc.powerOn();
}

void loop()
{
  byte msg[0];
  if (acc.isConnected()) {
    int len = acc.read(msg, sizeof(msg), 1); // read data into msg variable
    if (len > 0) {
      if (msg[0] == 1) // compare received data
        digitalWrite(LED_PIN,HIGH); // turn on light
      else
        digitalWrite(LED_PIN,LOW); // turn off light
    }
  } 
  else
    digitalWrite(LED_PIN , LOW); // turn off light
}

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

Previous post:

Next post: