A dirty and quick example of serial port communication in Android

Since I released UsbSerial I have received good feedback about its performance but I also have received messages with some legit doubts about how to use it. I finally overcame laziness and I have publish a little example of how to use UsbSerial correctly in a real app. Here it is the source code, just two java source code files πŸ™‚

Disclaimer: If you are looking for a serial terminal for Android, DroidTerm is what you need, this is just a quick example

An overall description of how it works:
– UsbService.java contains a Service to isolate all Usb operations. Interesting things happens there. If you need to change baud rate, stop bits and son those lines are located there. It is a good pattern to implement open connections in a Service so I encourage you to do it this way.

– When App starts, UsbService is created and will try to connect with an attached usb device. if there is one device compatible it will connect with it and data will be able to be sent and received. If no devices are attached, it will inform the user through a toast. The app will be still listening for new usb attached devices.

– Data received will appear in the white box, Send button will send the data wrote into the EditText.

Screenshot_2015-01-09-17-52-48

Although pretty simple and it does not have any particular goal (besides being an explanatory app), it could have some bugs so If you find something just let me know opening an issue on github.

Happy coding!

Advertisements

36 thoughts on “A dirty and quick example of serial port communication in Android

  1. Thanks for library, it has been brilliant.
    I’m trying to connect to two devices to two separate USB ports.
    – Device ID 1002 is connected to the serial port I need to transmit to.
    – Device ID 2002 is connected to a serial device I need to monitor.
    How do I connect to two serial ports using your library?

    • Hi Rick,
      I didn’t even try to connect two separate Usb ports (I thought about it though).I wouldn’t dare to state that this will work but I would try to instantiate two instances of UsbSerial with this constructor:
      public UsbSerialDevice(UsbDevice device, UsbDeviceConnection connection) //UsbDevice and UsbDeviceConnection correctly initialized before

      Each of them will create and handle their own threads so there shouldn’t be no problem if Android behaves correctly πŸ™‚
      I would like to give it a try soon.

      • Thanks. I’m not sure how to implement that. I’ve been trying to set up two connections & serial ports but get lost in threading.

        Do I put the constructor in usbservice and call it from where?

        Rick

  2. I keep getting Usb Device Not Supported messages when attempting to connect to either an FTDI or a Prolific PL2303TA. Both of these work with DroidTerm. Doesn’t DroidTerm use the same serialtousb library?

    • Hi,
      Yes, it should work. I just added some changes right now to SerialPortExample because I spotted an error with CDC in the library UsbSerial some days ago. Hope it helps!

  3. THANK YOU for this example! I got it working in minutes with my XBees and an OTG adapter cable for my Nexus 7. So much easier than trying to download, install and debug the other Android serial code I found

  4. hi,
    I have the same problem with DroidTerm and SerialPortExample.
    I have a device(CP2102) that continuously produces data packages and when socket is connected app starts to receive packages, but after 2-3 seconds of transfer window stops to indicate any process, the program stops responding to any clicks and there appears a message with information that program is not responding.(Prestigio pmp3007c3g, Android 4.2.2) Can you advise something?

    • Hi!
      I am not sure about what is the problem but we are going to try something. I’ve updated SerialPortExample with a new version of UsbSerial that will force 4.2.2 devices to use the synchronous api (less buggy on lower Android versions). Give it a try please.

  5. Thanks for answer. I installed the latest version, but the problem remains (and also checked with 4.4). It seems that our device produces packages too often (2.5 ms) and continuous output and processing of this data is not the best solution. Anyway thank you for this example. πŸ™‚

  6. I used android studio to import the project. I finally got it but my CP210xx only gives the first few lines of print. I tried a different arduino sketch and it was better but the printed text was binary hex looking and it too seemed to stop. Baud rates match. What is needed to keep the data flowing? I want to send the data to android and have an app read it and react to the data. I was hoping this example would lead the way. Its cool just to connect at all but I want more of course.

  7. OK, thanks. I tried DroidTerm and the data flows great with each newline from the arduino.getting displayed. The example would fill the white box and then not show any new data. What I’m trying to do is port a Processing sketch that reads serial and then uses the data to draw a box that rotates according to roll, pitch, yaw. I tried a different library and it just crashes the processing sketch on android. Take out the serial and the sketch works on android. Just need serial, but its a high hurdle.

  8. Hi , Great work on the UsbSerial.
    I tried on my LG G3 phone and its works using DroidTerm .
    However, when I connect the same arduino to same phone with your SerialPortExample it said:
    USB Ready
    USB device not supported.
    Can you enlighten me on this?
    Thanks a lot in advance.
    WK

  9. I noticed in the mainactivity.java there is a method:
    public void handleMessage(Message msg)
    {
    switch(msg.what)
    {
    case UsbService.MESSAGE_FROM_SERIAL_PORT:
    String data = (String) msg.obj;
    mActivity.get().display.append(data);
    break;
    }

    I don’t know the language enough but it’d be nice to use something that keeps display.append(data) going.

  10. Here I am again. I have a MainActivity that uses your code to start the USB connection, I get the toast messages, and I have a fragment that is a PApplet. I have no clue how to get the MyHandler to send the msg.obj to my fragment as a string. I’ve tried a lot of crazy stuff like changing the handleMessage to a String and then returning msg.obj, but cant change the type from void. I would pay you just to clue me in if interested.

    • Yippee, I got it. I use your code to read my arduino on the USB and my code to get my data from the main activity, then my processing code uses it to draw a cube that mimics the orientation of the arduino/sensors. It’s pretty cool to do that on a tablet. Thank you for the code. I stand on the shoulders of a giant.

  11. Hi felhr,
    I have built an App using your library and usbService.
    When I rotate the device several times, the UsbService will rebuilt for the first two times.
    Then the UsbService cannot find the usb serial device.
    I tried to unbind and and rebind the service, however, it doesn’t help.
    I dont even get the cdc control messages.

    Neither do I know if the problem occurs due to your usbservice or the device nor I can isolate the problem further.

    Is there a changelog for your recent changes?
    I have been building the app since september 2015 using an old version from beginning 2015.

  12. Hi
    I was trying to communicate to a windows or Linux PC USB instead of arduino. I did modify the device ID to 0x16b9 etc however I can’t see any data being received at the PC end through putty com port connection. I would be highly grateful if you could help.

    • You should use USB to serial converters in both sides of the communication. Something like this:
      PC USB to Serial Converter Serial to USB Converter Android phone

      • Hi thanks for your reply. For now I got hold of an OTG cable and connected hp pen drive (mass storage device) with vendor Id as 0x3f0 and product id as 0x5a07. I tried to add a new connection in pl203 id list.. however USB serialdevice.open () still returns false. Please help me in this regard

  13. Hello,

    i am trying to connect a FTDI USB Serial Chip to Android.
    For my project it is important, that the communication works without the main app. So if the App is closed all should work like before, when the App was open.

    How can i implement this? I think a service. But Service maybe killed by android after some time?
    It is also important to recognize a serial event immediately within milliseconds.

    Do you have any idea on that?

    Thank you
    Regards Danie

  14. Could this work for Android wear? Trying on a huawei watch but receiving “UsbService.ACTION_NO_USB”. Currently communicating with the watch using Android Intents via ADB, but its really slow

  15. Hey Felhr,

    I am trying to communicate with CDC device using examplesync, it is able to read eventful data generated by CDC device, but sending request/command using send button click to CDC device doesnt return any response (valid or error).

    However using DroidTerm I am able to receive data as well as send request.
    While using DroidTerm adding any request in blue area(terminal) and tapping of enter key CDC device returns valid response.

    Do I need to take care on which line I am send the instructions and data respectively. Please suggest.

  16. please help me
    i tried to do that, but my app can listening the data that trasmit the device but it canΒ΄t send data to device

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s