USB On-the-go capability in Android devices has now become more available in the market. And why wouldn’t it be? This feature, nicknamed OTG, enables you to use your flash drives, keyboards, mice and even printers with just your phone! What’s more interesting is it can also enable you to communicate and control your microprocessors using your Android device without the need for additional modules – just a cable. In this article, we will see how this communication can become possible. To demonstrate, we will control the behavior of an LED and send messages to another very popular item in the electronics world – the Arduino.
The shorter end of the stick is Arduino’s side. In your Arduino, simply upload this code:
int ledPin =13;
voidsetup(){
Serial.begin(9600);
Serial.setTimeout(200);
pinMode(ledPin, OUTPUT);
}
voidloop(){
if (Serial.available()){
String c = Serial.readString();
if (c.equals("TONLED")) digitalWrite(ledPin, HIGH);
elseif (c.equals("TOFFLED")) digitalWrite(ledPin, LOW);
else Serial.print(c);
}
}
In the above sketch, we are simply waiting for the data arriving at our serial line and performing actions based on the data received. For instance, turning on the LED ledPinrequires a TONLEDmessage from our Android device. You’ve probably noticed that there are no special libraries or methods in our Arduino sketch. That’s a great thing because it tells us that the system is not exclusive to Arduino and will work with any microcontroller that supports serial communication.
Let’s now move on to Android’s side. The first step is to create an Android project and add the necessary components. In the project we created, we added extra components for user convenience. For learning and testing purposes, only the following are necessary:
Text Field – used to get input data by the user, which will be sent to and echoed by the Arduino
Toggle Button – used to control the behavior of the LED
Start Button – used to open the serial port
Send Button – used to send messages to Arduino
Text View – used to display logs
To simplify the setup and processes, we will use the UsbSerial library by felHR85. There are a lot of libraries you can choose from. In case you have other preferences, feel free to modify and adapt to your preferred library.
In the build.gradle of your project, add jitpack. Jitpack is a very awesome tool that enables us to get a Git project into our build.
The next items that we will present here will not be discussed thoroughly, but you can refer to Android's official documentation for details. Before trying to start the communication, you must seek permission from the user. To do this, create a broadcast receiver. This receiver listens for the intent that gets broadcasted when you call requestPermission(). Only when granted can we proceed to opening the connection and setting parameters for the Serial communication.
privatefinal BroadcastReceiver broadcastReceiver =new BroadcastReceiver(){@OverridepublicvoidonReceive(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()){
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);}else{
Log.d("SERIAL","PORT NOT OPEN");}}else{
Log.d("SERIAL","PORT IS NULL");}}else{
Log.d("SERIAL","PERMISSION NOT GRANTED");}}elseif(intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)){
onClickStart(startButton);}elseif(intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)){//can add something to close the connection}};};
On your onCreatemethod, declare the intent and register your broadcast receiver to start and stop the serial connection.
In our application, we created a start button to start the connection when pressed. In the method that corresponds to the onClick action of our button, we add the following:
The code above searches for vendor IDs 1027 or 9025 – the vendor ID’s associated to FTDI or Arduino. The vendor ID equal to 9025 is the more popular and more common value based on other articles in the internet, but mine has an ID of 1027. The easiest way to know is to just print the vendor IDs detected by the Android device. If the vendor ID matches the expected ID for our device, we will call the requestPermission() method. With this, the intent will be broadcasted and picked up by our receiver, starting and opening the connection. Once communication is opened, we can start sending and receiving data. To receive from Arduino, simply add the codes below. Note that we are appending the data received to the text view.
private UsbSerialInterface.UsbReadCallback mCallback =new UsbSerialInterface.UsbReadCallback(){//Defining a Callback which triggers whenever data is read.@OverridepublicvoidonReceivedData(byte[] arg0){
String data =null;try{
data =new String(arg0,"UTF-8");
data.concat("/n");
tvAppend(displayView, data);}catch(UnsupportedEncodingException e){
e.printStackTrace();}}};privatevoidtvAppend(final TextView tv,final CharSequence text){
runOnUiThread(new Runnable(){@Overridepublicvoid run(){if(text !=null){
tv.append(text);}}});}
Sending data is easier. We only need to get user input from the text field, and send it to the connected device.
To control the LED in Arduino, simply add the code below. You are free to change TONLED and TOFFLED to whatever names you want. Just don’t forget to adjust the Arduino code as well.
And… were done! Additional tips, we can add a checker to confirm that the serial connection is already open. This saves us from crashes due to attempts to send serial data while the connection is still closed. We can also add clear buttons, or place the text view inside a scroll view then automatically scroll to end of page using:
That’s it. If you want to extend your phone’s sensors, or if you want to add storage, wireless and messaging capability, camera and orientation sensors in your microprocessor project with just one device, USB On-the-Go, may be your way to go. A demo application, SimpleArDroid by YMSoftLabs can be downloaded from Google Play. Here's a video of how the system works.