Sunteți pe pagina 1din 17

(/) let's make Explore (/tag/type-id/) Login (/account/login/)

Contests (/contest/) | Sign Up (/account/gopro)


Classes (/classes/)

Publish (/about/create.jsp)
Featured: 3D Printing Class (https://www.instructables.com/class/3D-Printing-Class/) Arduino (/tag/type-id/category-technology/channel-arduino/)

Sewing (https://www.instructables.com/tag/type-id/category-craft/channel-sewing/)

Control sensors, motors,


Fast Raspberry Pi Builder actuators & more with our free
Cayenne drag & drop project builder.

Arduino Android USB Serial Communication With OTG Cable by


vamsikurre (/member/vamsikurre/) in software (/tag/type-id/category-technology/channel-software/)

Download h (/id/Arduin-Adroid-USB-Serial-Communication/) 11 Steps .

Collection I Made it! Favorite Share

About This Instructable

License:
8 45.289 views
34 favorites

(/le/F11NFGKIJUCPG52/)
vamsikurre
(/member/vamsikurre/)
Follow 30

(/member/vamsikurre/)
More by vamsikurre:
(/le/FTBF0GCIJIX7AA7/)

I have made an Arduino based night lamp using photo resistor and problem (/id/Simple-LED-

with that is light levels was dierent from place to place, when I am testing I
have used a value as a threshold to switch on the light and after xing it in its
nal position that value is way o. Strip-Party-Lights-Using-Arduino/)

So, to get the correct value I have to data log the photo resistor reading after
xing the light in place, which was a bit harder, because I cannot leave my
(/id/Arduin-Adroid-
laptop outside for data logging for a whole day. So I need a portable solution to
my problem.

Another project was, water supply near my place was limited, we get water only
USB-Serial-Communication/)
at xed timings. so I made a device to turn on water motor at a xed timings of
day. I havent made any user interface for that device to change timings
because timings get to change very infrequently. So I need a way to change
(/id/Repair-and-
timings without connecting laptop and recompiling Arduino code, that would be
complicated for my parents.

So I decided to make an android app that would send serial data to Arduino to
Upgrade-Dodgy-Mouse/)
change timings of water motor. Check out our new classes! >> (/classes/?utm_medium=cta&utm_source=banner)
In this instructable, I will explain how to create an android app that can
communicate with Arduino by USB OTG cable, If you dont care about how to
just download .apk le and install it in your phone to communicate with arduino.

Serial_monitor.apk
Download (https://cdn.instructables.com/ORIG/FH2/UY6R/IJUCRORL/FH2UY6RIJUCRORL.apk)
(https://cdn.instructables.com/ORIG/FH2/UY6R/IJUCRORL/FH2UY6RIJUCRORL.apk)
Ad Fast Raspberry
Setapp. Novo Jeito de Ter Apps
+ de 60 apps gratuito por 30 dias. No exige
carto. Assine o Setapp agora!
Pi Builder
explore.setapp.com

Control sensors, motors,


actuators & more with our free
drag & drop project builder.

Step 1: Downloading Android Studio

Cayenne

(/le/FXXWFMRIJUCPE65/)

1. Get the android studio from http://developer.android.com/sdk/index.html


2. Click on download android studio button to start downloading
3. Agree to terms and conditions and your download should start
File will be an exe le and size would be around a gig

Check out our new classes! >> (/classes/?utm_medium=cta&utm_source=banner)


Step 2: Installing Android Studio

(/le/FV7PGYIIJUCPE7G/)

Show All Items

Install the exe le by going through some basic installation steps


At the end it will install latest SDK version automatically, let it complete.
Finally you should get welcome screen for android studio.
Check out our new classes! >> (/classes/?utm_medium=cta&utm_source=banner)
Step 3: Setting Up Android Studio

(/le/FO1UOEFIJUCPHWQ/)

(/le/F0ZAM4MIJUCPJHA/)

In the welcome screen you should see congure button, by selecting it you
should go to conguration page. There rst option would be SDK Manager,
by clicking that a new window will open by showing the details of current SDK.
There would be an option to launch standalone SDK Manager, by clicking
that good old SDK manager will be opened there you can add new SDK tool as
required.
Android studio has an emulator to test the android code, but unfortunately we
cannot use that for this scenario because this involves a physical device talking
to another device. Instead we can use an android phone itself to debug the
code.
Since we are using android device to debug the code we can just download
SDK Platform of that specic version of the device, rst know the android OS
version of the phone. In my case I am using Samsung note3 which has 5.0
(lollipop) so just download SDK Platform from Android 5.0.1 (API 21) that
should be enough.

Step 4: About the Library


Check out our new classes! >> (/classes/?utm_medium=cta&utm_source=banner)
(/le/FYNBAAPIJUCPMWG/)

The library I was using to make the communication is called physicaloid from
http://www.physicaloid.com/ (http://www.physicaloid.com/) which was last
updated 2 years ago and nal update was not working (for me at least). So after
discussing with people in github repository I managed to get the old working jar
le for that library.
By using this library we can not only communicate with Arduino but we can
upload compiled hex les into Arduino, this library has avrdude functionality
built-in.

physicaloidlibrary.jar
Download (https://cdn.instructables.com/ORIG/FNM/9MXQ/IJUCPKBD/FNM9MXQIJUCPKBD.jar)
(https://cdn.instructables.com/ORIG/FNM/9MXQ/IJUCPKBD/FNM9MXQIJUCPKBD.jar)

Step 5: Creating New Project in Android Studio

(/le/FVYFLCEIJUCPP4W/)

Check out our new classes! >> (/classes/?utm_medium=cta&utm_source=banner)


Show All Items

First I want to make an app that looks same as Arduino's serial monitor
window.
In the welcome screen of android studio there will be an option to create new
project, select Start a new android studio project
In the next page give your project name and location, then click next
In the next page select the platform for which we are developing application
and select correct version of your phone and click next
In the next page by default Blank activity will be selected and leave it as it is
for now. And in the next page name your activity (your main screen in the app).
Then click nish, newly created project will be opened in android studio and we
can work on it now

Step 6: Adding Library to New Project

(/le/F3D4LRCIJUCPTBX/)

Check out our new classes! >> (/classes/?utm_medium=cta&utm_source=banner)


Show All Items

In the top left side of the main screen there will be a drop down menu ladled as
android, change the option to project to see the directory structure of the
project.
In the directory structure by expanding app folder you can nd lib folder that
is the default folder to place our libraries.
Copy the physicaloidlibrary.jar le and paste it in libs folder
After pasting click sync project with gradle les button on the top.
Now the library is added we can use its features in our code.
Main activity that was automatically created when we rst created project will
be located in
App > src > main > java > YOUR_ACTIVITY
And layout will be located at
App > src > main > res > layout > activity_serial_monitor.xml

Step 7: Editing Manifest.xml

(/le/F6WD02YIJUCQ5DN/)

Manifest le is like main properties le for our project, It contains permissions


details and activity details
Manifest le is located in App > src > main > AndroidManifest.xml

Open the le and add

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

Line above
my manifest le looks like

Check out our new classes! >> (/classes/?utm_medium=cta&utm_source=banner)


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="serialmonitor.arduino.serialmonitor">

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

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".Serial_monitor"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
</application>
</manifest>

By adding that line we are asking permission of the user every time we connect
a USB device to OTG port

Step 8: Designing Layout

(/le/FXDQUDPIJUCQ85R/)

Show All Items

Editing should be done in content_serial_monitor.xml le


Check out our new classes! >> (/classes/?utm_medium=cta&utm_source=banner)
I have dragged 3 buttons, 1 edit text, 1 text view on to screen then renamed
and placed them in correct order.
Open opens the connection to USB device
Close closes the connection to USB device
Send sends data to Arduino
I also added a spinner to select baud rate and auto scroll feature as available in
serial monitor
Added this string array to strings.xml le located in app > src > main > res >
values > strings.xml

<resources>
<string name="app_name">Serial Monitor</string>
<string name="action_settings">Settings</string>
<string name="baud_prompt">Choose Baudrate</string>
<string-array name="baud_arrays">
<item>300 baud</item>
<item>1200 baud</item>
<item>2400 baud</item>
<item>4800 baud</item>
<item>9600 baud</item>
<item>19200 baud</item>
<item>38400 baud</item>
<item>576600 baud</item>
<item>744880 baud</item>
<item>115200 baud</item>
<item>230400 baud</item>
<item>250000 baud</item>
</string-array>
</resources>

Lets add good icon to our app


right click on the app > new > image asset
now browse the image le you want and set it as ic_launcher it will override the
default android icon

content_serial_monitor
Download (https://cdn.instructables.com/ORIG/F8L/F5P8/IJUCQ87O/F8LF5P8IJUCQ87O.xml)
(https://cdn.instructables.com/ORIG/F8L/F5P8/IJUCQ87O/F8LF5P8IJUCQ87O.xml)

Step 9: Adding Code to UI Elements

(/le/FSB06FMIJUCR6JB/)

I have attached complete java le Serial_monitor.java rst download it and


segments.
compare it to these small code Check out our new classes! >> (/classes/?utm_medium=cta&utm_source=banner)
First we have create all our UI elements and library variables

Button btOpen, btClose, btWrite;


EditText etWrite;
TextView tvRead;
Spinner spBaud;
CheckBox cbAutoscroll;

Physicaloid mPhysicaloid; // initialising library

next, in onCreate method we can initialise those variables we have created

btOpen = (Button) findViewById(R.id.btOpen);


btClose = (Button) findViewById(R.id.btClose);
btWrite = (Button) findViewById(R.id.btWrite);
etWrite = (EditText) findViewById(R.id.etWrite);
tvRead = (TextView) findViewById(R.id.tvRead);
spBaud = (Spinner) findViewById(R.id.spBaud);
cbAutoscroll = (CheckBox)findViewById(R.id.autoscroll);

mPhysicaloid = new Physicaloid(this); // setting the con


text for library

now we can display Required UI elements on screen, I am calling a method to


do this
That method takes boolean argument which species weather app is
connected to Arduino or not
setEnabledUi(false); // not connected to Arduino so false

//setEnabledUi method to set UI elements on screen


private void setEnabledUi(boolean on) {
if(on) { // if connected to device
btOpen.setEnabled(false); //hide open button (already op
ened)
spBaud.setEnabled(false); //hide baudrate selector
cbAutoscroll.setEnabled(false); // hide autoscroll
btClose.setEnabled(true); // display close button
btWrite.setEnabled(true); // display send button
etWrite.setEnabled(true); // display edittext field
} else { // if not connected to device
btOpen.setEnabled(true); //display open button
spBaud.setEnabled(true); //display baudrate selector
cbAutoscroll.setEnabled(true); //display autoscroll
btClose.setEnabled(false); // hide close button (already
closed)
btWrite.setEnabled(false); // hide send button
etWrite.setEnabled(false); // hide edittext field
}
}

Now we displayed everything as needed, now we can add actions to our


buttons.
listener method for open button, In this method we cover baudrate setting,
autoscroll option and connecting to device.

Check out our new classes! >> (/classes/?utm_medium=cta&utm_source=banner)


public void onClickOpen(View v) {
// setting the baudrate based on spinner
String baudtext = spBaud.getSelectedItem().toString(); // get the
text from spinner
//switch statement to check for baud rate
switch (baudtext) {
case "300 baud":
mPhysicaloid.setBaudrate(300);
break;
case "1200 baud":
mPhysicaloid.setBaudrate(1200);
break;
case "2400 baud":
mPhysicaloid.setBaudrate(2400);
break;
case "4800 baud":
mPhysicaloid.setBaudrate(4800);
break;
case "9600 baud":
mPhysicaloid.setBaudrate(9600);
break;
case "19200 baud":
mPhysicaloid.setBaudrate(19200);
break;
case "38400 baud":
mPhysicaloid.setBaudrate(38400);
tvAppend method to write received data to Textview

Handler mHandler = new Handler();


private void tvAppend(TextView tv, CharSequence text) {
final TextView ftv = tv;
final CharSequence ftext = text;
mHandler.post(new Runnable() {
@Override
public void run() {
ftv.append(ftext); // add text to Text view
}
});
}

Listener for close button

public void onClickClose(View v) { //when close button is pressed


if(mPhysicaloid.close()) { //close the connection to arduino
mPhysicaloid.clearReadListener(); //clear read listener
setEnabledUi(false); // set UI accordingly
}
}

Listeener for Send button

public void onClickWrite(View v) { // when send button is prressed


String str = etWrite.getText().toString()+"\r\n"; //get text
from EditText
if(str.length()>0) {
byte[] buf = str.getBytes(); //convert string to byte a
rray
mPhysicaloid.write(buf, buf.length); //write data to ar
duino
}
}

That's all everything is completed just connect your phone and run the program
it should install and open.

Serial_monitor.java
Download (https://cdn.instructables.com/ORIG/F3T/71R7/IJUCQVC1/F3T71R7IJUCQVC1.java)
(https://cdn.instructables.com/ORIG/F3T/71R7/IJUCQVC1/F3T71R7IJUCQVC1.java)

Check out our new classes! >> (/classes/?utm_medium=cta&utm_source=banner)


Step 10: Testing the App

(/le/FT2IVT4IJUCRFEW/)

(/le/FJBVQHDIJUCRCZO/) (/le/F3CPZL3IJUCRD11/)

Now connect phone and run the code by using play button on the top, now
device chooser dialogue pops up and ask's in which device should this app
install.
Note: if you did not nd your phone in the list try reinstalling the phone drivers.

If chosen correctly app should automatically install on phone make some


necessary adjustments to UI.
Run some test code and upload to arduino

Check out our new classes! >> (/classes/?utm_medium=cta&utm_source=banner)


void setup()
{
// Open serial communications and wait for port to open:
// Serial.begin(1200);
// Serial.begin(2400);
// Serial.begin(4800);
Serial.begin(9600);
// Serial.begin(14400);
// Serial.begin(19200);
// Serial.begin(38400);
// Serial.begin(57600);
// Serial.begin(115200);
}
void loop()
{
while(Serial.available() > 0) {
Serial.write(Serial.read());
}
}

Disconnect the phone from pc and connect to Arduino with OTG cable, and
send some data it should come back

serial_test.ino
Download (https://cdn.instructables.com/ORIG/FB6/6N6G/IJUCRBXD/FB66N6GIJUCRBXD.ino)
(https://cdn.instructables.com/ORIG/FB6/6N6G/IJUCRBXD/FB66N6GIJUCRBXD.ino)

Step 11: Other Uses

(/le/FSDXEV6IJUCRTVZ/)

Check out our new classes! >> (/classes/?utm_medium=cta&utm_source=banner)


(/le/FSP0HL4IJUCRUAE/) (/le/FCF9KR0IJUCRUB3/)

You can modify the layout and code to suit your needs and make an app for
each device you make separately

For example I have modied same project to work as a Interface for my motor
timer controller.

This can also be used for communicating with raspberry pi serial interface using
USB to UART converter as shown in adafruits
https://learn.adafruit.com/adafruits-raspberry-pi-lesson-5-using-a-console-
cable (https://learn.adafruit.com/adafruits-raspberry-pi-lesson-5-using-a-
console-cable) tutorial.

SerialMonitor.rar
Download (https://cdn.instructables.com/ORIG/FEY/ADCF/IJUCRMW6/FEYADCFIJUCRMW6.rar)
(https://cdn.instructables.com/ORIG/FEY/ADCF/IJUCRMW6/FEYADCFIJUCRMW6.rar)

Ad
Download Cleaner for Mac
Award-winning System Utility. Clean Mac les
Right Now!
MacKeeper.com

We have a be nice comment policy.



Please be positive and constructive. Check out our
w I Made it! new classes!
Add Images>> (/classes/?utm_medium=cta&utm_source=banner)
Post Comment
mesora (/member/mesora) 2 months ago Reply

hi there, thank you very much for your work and eort!

unfortunately i've the same "cannot open" issue as others few days ago.
i just spent hours to check every single step and cannot nd the problem.

i've a galaxy s6 (SM-G920F) with android 5.1.1. please help

mesora (/member/mesora) . mesora (/member/mesora) 2 months ago Reply

Still trying to nd the problem, is it possibly because i don't use an


arduino but a Nodemcu v3 board (ESP8266)?

it's arduino compatible so if, then only the USB_Vendor could be wrong..
how to nd and where to replace the NodeMCU vendor_id?

or am i wrong?

DreamW2 (/member/DreamW2) 2 months ago Reply

Can anyone help me to make a function that receives data in Android so I can
call it on other activities and use that data there?

ImaneT1 (/member/ImaneT1) 2 months ago Reply

when i try to open connection i always get "connot open" why?

MichalisG5 (/member/MichalisG5) 4 months ago Reply

When I try to open connection I always get "Cannot Open"... why?

ChaitanyaY1 (/member/ChaitanyaY1) . MichalisG5 (/member/MichalisG5)


3 months ago Reply
There might be three possibilities.

- Either you could have used wrong cable

- Check for connection settings in your setting option.

ejpaige86 (/member/ejpaige86) 4 months ago Reply

Hi, can you make a video of everything you did? That would be awesome!

LiangW1 (/member/LiangW1) 6 months ago Reply

Very informative guide!

As I am receiving values from the arduino A0 input, is it possible to plot it into a


graph?

Best Regards,
Weikang

X vamsikurre (/member/vamsikurre) (author) . LiangW1 (/member/LiangW1)


8
6 months ago Reply
Thanks, to plot graph dynamically as you receive
data from arduino pin you can use androidplot library which is open
source and easy to use.
Check out our new classes! >> (/classes/?utm_medium=cta&utm_source=banner)
you can nd more info at http://androidplot.com/
(http://androidplot.com/)

Regards,

LiangW1 (/member/LiangW1) . vamsikurre (/member/vamsikurre) Reply

6 months ago
Thank you for the advice! May I know what is the y axis
variable to plot the graph?

X vamsikurre (/member/vamsikurre) (author) . LiangW1 (/member/LiangW1)


8
6 months ago Reply
If X axis is your A0 output then Y axis should be time
I guess.
Dierence between points should be time interval that you are reading
the A0 output.

LiangW1 (/member/LiangW1) . vamsikurre (/member/vamsikurre) Reply

6 months ago
Im amazed and thankful for your prompt response! I meant
the y variable in your code. As I am reading a list of numbers from
Arduino, I simply want to plot them into a graph but I do not know what is
the name of the variable in your code.

X vamsikurre (/member/vamsikurre) (author) . LiangW1 (/member/LiangW1)


8
6 months ago Reply
You will get the data in the form of byte array in the
above code mPhysicaloid.read(buf, size);

line gets the serial data from arduino and populates it into 'buf' byte array
variable, I guess you need to convert that byte array into string or integer
to plot graph. you can use 'public void onRead(int size)' function to get
the event of receiving new data to update your graph.

Regards

| agis68 (/member/agis68) a year ago Reply


8
very good instructable...and interesting too...

where you get the USB adapter?


I guess with this and some extra module you can control anything through
relays...Also programming atmega chips. Has any limitation or just that ends
up to any imagination?

Thanks

X vamsikurre (/member/vamsikurre) (author) . agis68 (/member/agis68) Reply


8
a year ago
Thanks, that adapter is OTG cable for android can be found
very cheaply in ebay like this
http://www.ebay.com/itm/3x-USB-2-0-A-Female-to-Micro-B-Male-
Converter-OTG-Adapter-Cable-4-Smart-Phone-SN-/151832683413

Unfortunately their is no AVR compiler in the library so we cannot compile


text code in the android device but we can upload already compiled code
like .hex les to AVR chips.

X
|

nancyjohns (/member/nancyjohns)
Check out our new classes! >> (/classes/?utm_medium=cta&utm_source=banner)
8 Very nice. I must point out that the name of the instructable a year ago Reply

is, "Arduin Adroid USB Serial Communication." Did you


happen to mean, "Arduino Android USB Serial Communication?"

X vamsikurre (/member/vamsikurre) (author) . nancyjohns (/member/nancyjohns)


8
a year ago Reply
yes

FEATURED CHANNELS

Woodworking Paper Kitchen Hacks Puzzles Laser Cutting Space Homesteading 3D Printing Sewing
(/tag/type- (/tag/type- (/tag/type- (/tag/type- (/tag/type- (/tag/type- (/tag/type- (/tag/type- (/tag/type-
id/category- id/category- id/keyword- id/category- id/category- id/keyword- id/category- id/category- id/category-
workshop/channel-craft/channel- kitchen%20hacks/?play/channel- workshop/channel- astronomy/? home/channel- technology/channel-
craft/channel-
woodworking/) paper/) sort=FAVORITES) puzzles/) laser-cutting/) sort=FAVORITES) homesteading/) 3D-Printing/) sewing/)
Newsletter About Us
Join 2 million + to receive instant Who We Are (/about/)
DIY inspiration in your inbox. Advertise (/advertise/)
Contact (/about/contact.jsp)
enter email I'm in!
Jobs (/community/Positions-available-at-Instructables/)
Help (/id/how-to-write-a-great-instructable/)
Find Us Resources
Facebook (http://www.facebook.com/instructables) For Teachers (/teachers/)
Youtube (http://www.youtube.com/user/instructablestv) Artists in Residence (/air)

Twitter (http://www.twitter.com/instructables) Gift Premium Account (/account/give?sourcea=footer)


Forums (/community/)
Pinterest (http://www.pinterest.com/instructables)
Answers (/tag/type-question/?sort=RECENT)
Google+ (https://plus.google.com/+instructables)
Sitemap (/sitemap/)

Terms of Service (http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=21959721) |


Privacy Statement (http://usa.autodesk.com/adsk/servlet/item?siteID=123112&id=21292079) |
Legal Notices & Trademarks (http://usa.autodesk.com/legal-notices-trademarks/) | Mobile Site (https://www.instructables.com)
(http://usa.autodesk.com/adsk/servlet/pc/index?id=20781545&siteID=123112)
2016 Autodesk, Inc.

Check out our new classes! >> (/classes/?utm_medium=cta&utm_source=banner)

S-ar putea să vă placă și