Blog - Sketching with Hardware

Team 6 – The interaction between Arduino and an Android smartphone

Published on: | Author: Maximilian Frainzl | Categories: 2016a, Tutorials

Connecting your Arduino with an Android smartphone enriches your „Sketching with Hardware“ projects with a lot of additional features.

For our project „Confuseball“ we used it to receive a notification on the smartphone (and from there it was forwarded to a web application), whenever a player scores a goal. It also would’ve been possible to send back a message from the smartphone to the Arduino, e.g. for controlling some LEDs through the Android app.

In this tutorial I’m giving you an overview of three different possibilities on how to set up a connection between your Arduino and your Android smartphone and explain how you can set it up by yourself.


I. Android phone as a USB host

What you need:

  • Android smartphone which supports USB host mode (OTG support). You can find out if your phone supports it, either by googling or by installing the „USB Host Diagnostics App“ from the Play Store
  • Arduino. For our project we used an Arduino Uno Rev. 3
  • Arduino USB cable
  • USB OTG Adapter. It is needed to connect the USB cable of the Arduino to the micro-USB port of the Smartphone. We used this one:
    otgadapter

How to establish a connection between your Arduino and an Android application

1. First you need to create a new Android Studio project. If you have never done this before, please also refer to the official documentation:  http://developer.android.com/training/basics/firstapp/creating-project.html

2. In the second step, please download the „UsbSerial“ library JAR file (see link above). Copy it to the „libs“ folder of your project and then right-click it in the Android Studio file explorer and select „Add As Library“.

addlibrary

3. Then you need to open the „AndroidManifest.xml“ (you can find it in the „res“ folder of your project and add this line to the code:

<uses-feature android:name=”android.hardware.usb.host” />

addpermission

It gives the application the permission to use your phone as a USB host.

You can find a tutorial with a sample GUI, that allows you to send text to your Arduino and receive the same text back here:

http://www.allaboutcircuits.com/projects/communicate-with-your-arduino-through-android/

We took some parts of the following code and modified it for our needs.

4. First you need to add some imports and define some global variables:

// Imports used

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.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.felhr.usbserial.UsbSerialDevice;
import com.felhr.usbserial.UsbSerialInterface;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

// Global variables and Method to communicate with Arduino via USB

public final String ACTION_USB_PERMISSION = “confoosball.lmu.mff.confoosball.USB_PERMISSION”;
Button startButton, stopButton;
UsbManager usbManager;
UsbDevice device;
UsbSerialDevice serialPort;
UsbDeviceConnection connection;

5. Now we’re good to go to open a connection by using this method:

public void openConnection() {
HashMap usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry entry : usbDevices.entrySet()) {
device = entry.getValue();
int deviceVID = device.getVendorId();
if (deviceVID == 0x2341) //Arduino Vendor ID
{
PendingIntent pi = PendingIntent.getBroadcast(this, 0,
new Intent(ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device, pi);
keep = false;
} else {
connection = null;
device = null;
}
if (!keep)
break;
}
}
}

For our Arduino Uno Rev. 3 the device’s Vendor ID 0x2341 worked (it should work in most cases – if it’s not working google can help you to find yours).

This method will be called by the BroadcastReceiver (see next step), whenever the Arduino is connected.

6. In the next step the BroadcastReceiver is defined, which is there to ask the user for permission and also to start/stop the connection automatically, whenever a device is connected/disconnected:

private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted =
intent.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
if (granted) {
connection = usbManager.openDevice(device);
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) { // Set Serial Connection Parameters.
serialPort.setBaudRate(9600);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback);
Log.d("SERIAL", „SERIAL CONNECTION OPENED!“);

} else {
Log.d(“SERIAL”, “PORT NOT OPEN”);
}
} else {
Log.d(“SERIAL”, “PORT IS NULL”);
}
} else {
Log.d(“SERIAL”, “PERMISSION NOT GRANTED”);
}
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
openConnection();
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
serialPort.close(); // The connection is automatically closed, when the device is detached
}
};
};

For the Arduino Uno the standard parameters marked in red worked well, for other devices you might have to change them accordingly.

7. Now we come to the interesting part, where data is received from the Arduino:

UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() {
//Defining a Callback which triggers whenever data is read.
@Override
public void onReceivedData(byte[] arg0) {
String data = null;
try {
data = new String(arg0, "UTF-8");
/* Do something with the data, e.g.
if (data.equals("A")) {
countGoals("A");
} */
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};

You receive the data, that the Arduino sends you, as a String. Now you can do whatever you want to do with it. In our „Confuseball“ application we call at this point a method which counts the goals.

8. It’s also very easy to send a string message back to your Arduino. You can realize this with two lines of code:

String string = „Hello Arduino!“;
serialPort.write(string.getBytes());

9. The Arduino code for sending and receiving data is (as you might be used to it ;)) very simple:

void setup()
{
Serial.begin(9600); // Initialize connection
}
void loop()
{
char c;
if(Serial.available()) // Check if USB connected
{
c = Serial.read(); // Receive messages
Serial.print(c); // Send message, in this case the message received by the Arduino is sent back to the Android app
}
}


 

II. Realizing a Bluetooth connection

If you Android smartphone doesn’t support OTG but has Bluetooth, you can get a „HC-05 Bluetooth Module“ for your Arduino and realize a connection this way.

Since the smartphone that we used for the „Confuseball“ project has OTG support and was also able to provide power to the Arduino, we didn’t try out this method. But All About Circuits also provides a very good description on how it’s supposed to work. It’s very similar to the USB method described above and you can use the same Android app for it.


III: Using the USB port of the Arduino MEGA with the ADK

On the Arduino product overview page of the Arduino Mega ADK it says:
„NOTE: this product is currently retired and the documentation will not be kept up-to-date“
and also if you are doing some research on the Internet, you wont find any tutorial that is really up-to-date, using the ADK.

But nevertheless, it should be included in this blog post as a third possibility.
Here are some links that we found, which might help you to set up a connection:

Official ADK Android Developer Page

Softwaresupply.de

YouTube video by CODEPHENOM

Since we decided to use the USB host method, we didn’t try them out. But we found it, that you might need to use an older version of the Arduino IDE, in ordert to test the example scripts provided by the IDE.

IV: Comparison of the methods and summary

I would suggest to use one of the first two methods, because they are really easy to set up. If your smartphone supports OTG, it may also serve you as a power source.

Another advantage is, that you can use these methods with any kind of Arduino, maybe even with the Arduino mini and a bluetooth/USB module.

There is a lot of possibilities, that you can implement now by having the full bandwidth of the Arduino and your smartphone sensor modules/functionality.

If you want, you can check out our „Confuseball“ application, which uses the smartphone to count and display the goals, that the Arduino submits – or simply download the code of our Android and Arduino projects here. Have fun with your Arduino-Android projects 😉

linked categories 2016a, Tutorials

|

Write a comment

Comment

[…] It’s time to fix the selfie stick at the foosball. We take some pieces of plastic and fasten it with two nails. Now you can plug the selfie stick into the plastic rings. On the top of the stick you have your phone with our Android App and connected over OTG with your Arduino, which shows you the score, tracks the ball and then send the information to a web application. In our web application the score and the ball tracking are displayed. (If you want more information on how to connect your Arduino to an Android smartphone, go to our oth…. […]

[…] the Arduino <-> Android connection we used this great tutorial by former SWHardwarers. It eventually worked after a Tuesday Night-session and some lessons learned […]