Monday, May 9, 2016

Android-Arduino Communication via USB OTG


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;

void setup(){  
  Serial.begin(9600);
  Serial.setTimeout(200);
  pinMode(ledPin, OUTPUT);  
}  

void loop(){
  if (Serial.available()){
    String c = Serial.readString();
    if (c.equals("TONLED")) digitalWrite(ledPin, HIGH); 
    else if (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 ledPin requires a TONLED message 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.

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

Now, add the dependency to your module’s build.gradle.

compile 'com.github.felHR85:UsbSerial:4.3'

Moving on to our main activity, there are some variables that we wish to declare globally for convenience.

private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";

UsbDevice device;
UsbDeviceConnection connection;
UsbManager usbManager;
UsbSerialDevice serialPort;
PendingIntent pendingIntent;

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.

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()) {
                        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");
            }
        } else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
            onClickStart(startButton);
        } else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
            //can add something to close the connection
        }
    };
};

On your onCreate method, declare the intent and register your broadcast receiver to start and stop the serial connection.

pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(broadcastReceiver, filter);

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:

public void onClickStart(View view) {

    if (!isSerialStarted) {
        usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);

        HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
        if (!usbDevices.isEmpty()) {
            boolean keep = true;
            for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
                device = entry.getValue();
                int deviceVID = device.getVendorId();

                if (deviceVID == 1027 || deviceVID == 9025) { //Arduino Vendor ID
                    usbManager.requestPermission(device, pendingIntent); 
                    keep = false;
                } else {
                    connection = null;
                    device = null;
                }
                if (!keep)
                    break;
            }
        }
    }
}

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.
    @Override
    public void onReceivedData(byte[] arg0) {
        String data = null;
        try {
            data = new String(arg0, "UTF-8");
            data.concat("/n");
            tvAppend(displayView, data);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
};

private void tvAppend(final TextView tv, final CharSequence text) {
    runOnUiThread(new Runnable() {
        @Override public void 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.

public void onClickSend(View view) {
    String textInput = inputView.getText().toString();
    serialPort.write(textInput.getBytes());
}

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.

public void onClickToggle(View view) {
    if (isLedON == false) {
        isLedON = true;
        tvAppend(displayView, "\nLED TURNED ON\n");
        serialPort.write("TONLED".getBytes());
    } else {
        isLedON = false;
        serialPort.write("TOFFLED".getBytes());
        tvAppend(displayView, "\nLED TURNED OFF\n");
    }
}

You can close the connection using:

serialPort.close();

We are almost done. In your manifest file, add the following so that your application will be notified of an attached USB device. 

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

    <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=".MainActivity"
            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>
            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
            </intent-filter>
            <meta-data
                android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
                android:resource="@xml/device_filter" />
            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Create an xml folder inside the res folder and add device_filter.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <usb-device
        vendor-id="9025"/>
</resources>

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: 

mScrollView.smoothScrollTo(0, displayView.getBottom());

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.




References:
UsbSerial: A serial port driver library for Android v3.0
USBSerial
Communicate with Your Arduino Through Android


84 comments:

  1. Thank you ! Now i can create my own app :)

    ReplyDelete
  2. Cannot resolve symbol 'isSerialStarted'. Can you please explain why and how to solve it? Thank you.

    ReplyDelete
  3. I have got lots of ideas from this blog really it's a nice blog that provide me lots of information. Thank you.

    ReplyDelete
  4. Thanks For Sharing This Blog Very Useful And More Informative.

    Dell Boomi Training Training

    ReplyDelete
  5. Thanks for your great and helpful presentation I like your good service. I always appreciate your post. That is very interesting I love reading and I am always searching for informative information like this. Well written article
    Machine Learning With TensorFlow Training and Course in Muscat
    | CPHQ Online Training in Singapore. Get Certified Online

    ReplyDelete
  6. I have followed all the steps but I do not know in which files the indicated codes are modified or in which lines. Can someone pass me the complete code to check if it works? Please!

    ReplyDelete
  7. Red Hat Enterprise Linux System. The Certified Engineer takes care of various tasks such as setting kernel runtime parameters, handling various types of system logging and providing certain kinds of network operability. The professionals must have the ability to install networking services and security on servers running Red Hat Enterprise Linux.
    Red Hat Certified Engineer

    ReplyDelete
  8. Hi to everybody, here everyone is sharing such knowledge, so it’s fastidious to see this site, and I used to visit this blog daily.

    Data Science Training

    ReplyDelete
  9. interesting piece of information, I had come to know about your web-page from my friend, i have read atleast eight posts of yours by now, and let me tell you, your blog gives the best and the most interesting information. This is just the kind of information that i had been looking for, i'm already your rss reader now and i would regularly watch out for the new posts, once again hats off to you! Thanks a million once again, Regards,
    Salesforce Training in Chennai | Certification | Online Course | Salesforce Training in Bangalore | Certification | Online Course | Salesforce Training in Hyderabad | Certification | Online Course | Salesforce Training in Pune | Certification | Online Course | Salesforce Online Training | Salesforce Training

    ReplyDelete

  10. This Is Really Useful And Nice Information. ราคาผลบอลสด
    This are such great articles. ราคาผลบอลสด This articles can help you to make some new ideas.
    https://sakukrub98.hatenablog.com/entry/2020/08/07/123455?_ga=2.62469551.2071274699.1596422357-1286484823.1596077192 I appreciate for reading my blogs.


    ReplyDelete
  11. This is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the good work. I have been meaning to write something like this on my website and you have given me an idea.
    Best Institutes For Digital Marketing in Hyderabad

    ReplyDelete
  12. Fantastic blog extremely good well enjoyed with the incredible informative content which surely activates the learners to gain the enough knowledge. Which in turn makes the readers to explore themselves and involve deeply in to the subject. Wish you to dispatch the similar content successively in future as well.

    Data Science Course in Bhilai

    ReplyDelete
  13. I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well.

    Data Analytics Training in Gurgaon

    ReplyDelete
  14. Really it was an awesome article...very interesting to read.. You have provided an nice article....Thanks for sharing.

    Java Training in Chennai

    Java Course in Chennai

    ReplyDelete
  15. Really it was an awesome article...very interesting to read.. You have provided an nice article....Thanks for sharing.

    SEO Training in Hyderabad

    ReplyDelete
  16. Good Information,
    SEO Training In Hyderabad at Digital Brolly

    ReplyDelete
  17. Really wonderful blog! Thanks for taking your valuable time to share this with us. Keep us updated with more such blogs.
    AWS Training in Chennai
    AWS Online Training
    AWS Training in Coimbatore

    ReplyDelete
  18. valuable blog,Informative content...thanks for sharing, Waiting for the next update…
    reactjs training in chennai
    react js course in chennai

    ReplyDelete
  19. Glad to chat your blog, I seem to be forward to more reliable articles and I think we all wish to thank so many good articles, blog to share with us.
    digital marketing courses in hyderabad with placement

    ReplyDelete
  20. Great post. keep sharing such a worthy information


    ReplyDelete
  21. Hey!! This is such an amazing article that I have read today & you don't believe that I have enjoyed a lot while reading this amazing article. thanx for sharing such an amazing article with us. SEO Company in Hyderabad

    ReplyDelete
  22. Really nice blog. thanks for sharing such a useful information.
    Kotlin Online Course

    ReplyDelete
  23. Perfect blog to read in free time to gain knowladge.Sattaking

    ReplyDelete
  24. Well explained article, loved to read this blog post and bookmarking this blog for future.http://spencerdcax01222.blogprodesign.com/27069059/all-about-satta-king

    ReplyDelete
  25. Very good info. Lucky me I discovered your site by chance (stumbleupon). I have saved it for later! Here is my web site:https://www.hostingendomeinen.nl/support/profile.php?section=personal&id=586656

    ReplyDelete
  26. Very good info. Lucky me I discovered your site by chance (stumbleupon). I have saved it for later! Here is my web site:http://stephenmvzd46780.newbigblog.com/9176082/what-s-satta-king

    ReplyDelete
  27. Great blog.thanks for sharing such a useful information
    QTP Training

    ReplyDelete

  28. Infycle Technologies, the top software training institute and placement center in Chennai offers the best
    Data science training in Chennai
    for freshers, students, and tech professionals at the best offers. In addition to Digital Marketing, other in-demand courses such as DevOps, Big Data, Cyber Security, Python, Selenium, Big Data, Java, Power BI, Oracle will also be trained with 100% practical classes. Call 7504633633 to get more info and a free demo.

    ReplyDelete
  29. List with Confidence Real Estate Company all of our agents are long time locals and experts in the local real estate market. Find out about them here.

    Real Estate Agents Near Me
    Gta Real Estate Market
    <a

    ReplyDelete
  30. Very informative and interesting content. I have read many blog in days but your writing style is very unique and understanding. If you have read my articles then click below.

    himalayan salt lamp spiritual benefits
    himalayan salt spiritual benefits
    himalayan rock salt cooking tile

    ReplyDelete
  31. There is a great deal that can be learned through the SMM coursecba it

    ReplyDelete
  32. This comment has been removed by the author.

    ReplyDelete

  33. Extraordinary blogs went amazed with the content that they have developed in a very descriptive manner. This type of content surely ensures the participants to explore themselves. Hope you deliver the same in the near future as well. Gratitude to the blogger for the efforts.

    Data Science Training

    ReplyDelete
  34. Outdoor Dining Chairs

    Outdoor dining chairs are trendy, comfortable and create a magnificent outdoor seating experience. Outdoor chairs in different colors, styles and shapes are always a perfect fit for one's outdoor dining experience.

    Outdoor dining chairs are made in such a way that they can blend in with any background. Even though they are primarily designed to be used outdoors, you can choose to place them indoors at times as well.

    ReplyDelete
  35. This is a very nice post you shared, I like the post, thanks for sharing.
    cyber security certification malaysia

    ReplyDelete
  36. I see some amazingly important and kept up to a length of your strength searching for in your on the site
    cyber security course malaysia

    ReplyDelete
  37. I think you're reading my mind 토토!You seem to know a lot about this.It's like writing a book.Instead of taking a few pictures 메이저토토사이트, a great blog will give you better information about the message.It's a wonderful reading 온라인카지노.I'm sure I'll be back.

    ReplyDelete
  38. I later this message,and that i wager that they having a laugh to log on this say,they shall proclamation you'll a satisfying web site to make a advocate,thank you for sharing it to me... Avast Secureline VPN License

    ReplyDelete
  39. Thanks for sharing this excellent post, I am going to share it as an external reference link in a post I am writing on Guest Posting.

    ReplyDelete
  40. Hairextensionscottsdale guarantees best micro ring hair extension at most cost-effective prices available on the market Micro Ring Hair Extensions Scottsdale Visit today!

    ReplyDelete
  41. Glad to read this informative and helpful post about cv recoders, it shares lots of great information, keep sharing such posts. check it out wyze coupons

    ReplyDelete
  42. Great! It sounds good. Thanks for sharing, For more detail visit on my page Free Reaction Time Test

    ReplyDelete
  43. I'm sorry for acting like I want to jump on you. I just like taking the piss out of uplifting, viral internet things. our clinbio.com

    ReplyDelete
  44. A good piece of informational writing. I'm grateful you shared.
    React-Js training in hyderabad

    ReplyDelete
  45. Great Blog Thank you for sharing..

    ELearn Infotech offers Python Training in Hyderabad Madhapur. Our Python course includes from Basic to Advanced Level Python Course. We have designed our Python course content based on students Requirement to Achieve Goal. We offer both class room Python training in Hyderabad Madhapur and Python Course Online Training with real time project.

    ReplyDelete
  46. great article, felt good after reading.worth it https://rudrasa.com/mern-stack-course-in-hyderabad/

    ReplyDelete
  47. Welcome to iTech Manthra, your premier destination for top-notch seo training in hyderabad
    ! We specialize in providing comprehensive courses that o

    ReplyDelete
  48. Refrigerated Courier Services – Texas provide rapid, temperature-controlled delivery for sensitive goods. Utilizing advanced refrigeration technology and skilled logistics, these services ensure perishable items like food and pharmaceuticals remain fresh and safe, meeting the demands of Texas's diverse industries.

    ReplyDelete
  49. USB On-the-go (OTG) capability in Android devices is a game-changer, allowing users to easily connect flash drives, keyboards, mice, and even printers directly to their phones. This convenience makes mobile computing more versatile and efficient. For the best interior solutions, check out the best fit out companies in Dubai.



    ReplyDelete
  50. Investigating USB OTG connectivity between Android and Arduino creates interesting opportunities for creative ideas and smooth integration. It's a great approach to incorporate adaptable hardware solutions with mobile technology. In order to make your event truly unforgettable, don't forget to look into excellentCatering services Odessa Texas, if you're organizing one.

    ReplyDelete

  51. It's crucial for abatement contractors in Edmonton to adhere to strict safety demolition expert in Edmontonstandards to ensure the health and well-being of the community. Proper training and certification are essential for handling hazardous materials. Choose a reputable contractor for peace of mind.

    ReplyDelete
  52. Ordering coffee online in Dubai is such a convenient way to get your caffeine fix coffee beans dubaiwithout leaving the comfort of your home. With just a few clicks, you can enjoy your favorite brew delivered right to your doorstep!"

    ReplyDelete
  53. Exceptional quality and efficiency! Arjes Machinery Canada sets the standard for innovation in the industry."dust suppression units Edmonton

    ReplyDelete
  54. Android devices with USB On-the-Go (OTG) functionality are getting more and more popular, and for good reason. This feature increases the versatility of the gadget by making it simple for users to connect flash drives, keyboards, and more. Enjoy the ease of OTG, but don't forget to add a little additional joy to your day by indulging in some delicious delicacies fromشراء شوكولاتة.

    ReplyDelete
  55. For tech aficionados, Android-Arduino connection via USB OTG is revolutionary since it makes mobile devices and hardware projects seamlessly integrated. This capacity creates countless opportunities for automation and innovation. Maintaining optimal performance in every setting requires thorough heavy detergent cleaning with powerful detergents, just as precision is crucial in technological undertakings.

    ReplyDelete
  56. The article emphasizes how USB On-the-go is becoming more widely available and versatile on Android devices, making it easier to connect a variety of accessories. It examines the ways in which this characteristic facilitates microprocessor control and communication, highlighting the possible uses for it. Enhance your creative adventure by pairing your reading with the delectable flavors of قهوة عربيةas you venture farther into the realm of electronics.

    ReplyDelete
  57. best pasta dining in Abu Dhabi, offering classic Italian dishes like creamy Alfredo, savory Bolognese, and rich Carbonara. Made with fresh ingredients, each dish delivers authentic Italian flavors perfect for pasta lovers.

    ReplyDelete
  58. Edmonton cracked basement wall repair prevents water intrusion, mold growth, and further structural damage. Prompt repairs help maintain your foundation’s integrity and safeguard your home from costly issues.

    ReplyDelete
  59. herbal honey combines pure honey with beneficial herbs, creating a nutrient-rich blend that supports immunity, energy, and overall vitality. Known for its soothing and antioxidant properties, it’s a natural choice for promoting well-being and enhancing daily health routines.

    ReplyDelete
  60. This blog consistently provides valuable insights and updates on the latest advancements in data science..data science classes in chennai

    ReplyDelete