Arduino Android Serial Communication

hingxyu
4 min readJun 8, 2019

--

In this tutorial, I would show you how to establish a serial communication channel between Android and Arduino through USB cable and send data bidirectionally.

Requirements

Hardware:

  1. Android Phone
  2. Arduino (theoretically from any type, but I’ll be using Arduino Uno)
  3. USB 2.0 Cable Type A/B (for Arduino)
  4. OTG Cable (On The Go)
  5. Normal USB Cable (for transferring the data from Android Studio to your phone)

Software:

  1. Android Studio
  2. Arduino IDE

Wiring and Setup

Wiring must be established in the following way:

Android-Arduino Setup

Working on the Android Side

We would be using a simple and powerful Omar Aflak’s - Arduino Library for establishing serial communication.

1. Adding the dependency:

a) Add the following line of code to your module build.gradle file.

implementation 'me.aflak.libraries:arduino:1.3'

b) Add jitpack to your project.build.gradle file.

allprojects {
repositories {
jcenter()
maven { url "https://jitpack.io" }
}
}

2. Understanding the API:

Given below are the most useful methods and callbacks which would serve the required purpose.

a) Constructor: This is used to create a new Arduino instance (Essentially, as you can guess, its a requisite for implementing further methods and callbacks).

Arduino arduino = new Arduino(Context);

b) Arduino Listener: There is a listener which you can set this way.

arduino.setArduinoListener(new ArduinoListener(...))

The listener implements the following methods:

onArduinoAttached(UsbDevice device) // arduino plugged in. Here you should call arduino.open(device)onArduinoDetached() // arduino plugged outonArduinoMessage(byte[] bytes) // arduino sent a message through Serial.print()onArduinoOpened() // connection with arduino openedonUsbPermissionDenied() // when user denies the USB permission

c) Method for Sending Data: For sending messages to Arduino use the following method:

String msg = "Hello Arduino! This is Android.";
arduino.send(msg.getBytes());

3. Implementation:

Here is the complete implementation of a full-fledged application for arduino-android communication.

a) MainActivity.java

<your package name>import android.hardware.usb.UsbDevice;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import me.aflak.arduino.Arduino;
import me.aflak.arduino.ArduinoListener;
public class MainActivity extends AppCompatActivity implements ArduinoListener { private Arduino arduino;
private TextView displayTextView;
private EditText editText;
private Button sendBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayTextView = findViewById(R.id.diplayTextView);
editText = findViewById(R.id.editText);
sendBtn = findViewById(R.id.sendBtn);
displayTextView.setMovementMethod(new ScrollingMovementMethod()); sendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String editTextString = editText.getText().toString();
arduino.send(editTextString.getBytes());
editText.getText().clear();
}
});
arduino = new Arduino(this);
}
@Override
protected void onStart() {
super.onStart();
arduino.setArduinoListener(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
arduino.unsetArduinoListener();
arduino.close();
}
@Override
public void onArduinoAttached(UsbDevice device) {
display("arduino attached...");
arduino.open(device);
}
@Override
public void onArduinoDetached() {
display("arduino detached.");
}
@Override
public void onArduinoMessage(byte[] bytes) {
display(new String(bytes));
}
@Override
public void onArduinoOpened() {
String str = "arduino opened...";
arduino.send(str.getBytes());
}
@Override
public void onUsbPermissionDenied() {
display("Permission denied. Attempting again in 3 sec...");
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
arduino.reopen();
}
}, 3000);
}
private void display(final String message){
runOnUiThread(new Runnable() {
@Override
public void run() {
displayTextView.append(message);
}
});
}
}

b) activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Enter the text below:" />
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp" />
<Button
android:id="@+id/sendBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:text="Send" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Received Messages From Arduino:"
android:layout_marginTop="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"/>
<TextView
android:id="@+id/diplayTextView"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_margin="5dp"
android:layout_weight="1"
android:background="@android:color/darker_gray"
android:textColor="@android:color/black"
android:textSize="16sp"
android:scrollbars = "vertical" />
</LinearLayout>

Working on the Arduino Side

Arduino code is relatively simple. It simply echoes back whatever it receives on the serial port.

void setup() {
// initialize serial communication at 9600 bits per second:
Serial.begin(9600);
}
void loop() {
char incomingByte;
// If there is a data stored in the serial receive buffer, read it and print it to the serial port as human-readable ASCII text.
if(Serial.available()){
incomingByte = Serial.read();
Serial.print(incomingByte);
}
}

That's it! You are good to go 😉. Communication has been established bidirectionally. The data sent from Android will be echoed back by Arduino. I have added the screenshots below so that you see the visual imprint of the above code without running it (if you are lazy enough like me 😛).

Screenshots

Arduino Android Serial Communication Validation
The Initial Request for Permission

Thanks for taking the time to read this blog. Hope it was able to make some good contributions to your knowledge base 😃.

--

--

hingxyu
hingxyu

Written by hingxyu

Avid Techno-geek; Interested in cross-disciplinary research in subdomains like deep learning, computer vision, computer graphics, embedded systems.

Responses (5)