Coding USB-Serial using Android Studio.

Written by: Holguer A. Becerra

Requirements:

  • Android Studio 2.1 or superior.
  • USB-Serial FTDI232 converter
  • OTG cable.
  • Attachments

As everyone knows, we are used to using UART/Serial protocols to create communication channels between our programable devices. However, it is not always handy for beginners to have an explained and detailed tutorial about it, which drives me to write this simple but useful tutorial that you might find useful for your class projects or whatever your idea could be.

 

  1. First, you need to have installed Android Studio 2.1 or superior, in this case I will work with Android 2.1.2.
  2. After you have installed Android Studio, you need to download this JAR file, which contains the driver to access FTDI Serial devices. In this case FTDI 232 chips.
  3. Now, open Android Studio, let’s begin by creating a new project.









  4. After creating the new project, it is gonna appear something like the following


  5. We are going to click on the tap “app” and select the folder “Lib”


  6. Now if we expand the folder “FPGALover_USB_Serial” we are going to observe in detail all our project directory.


  7. Now expand the folder “app”, and there should be a folder called “Lib”


  8. Paste on this folder the jar you downloaded.


  9. After pasting it, right-click on the file “usbserial.jar”, and choose “Add As Library…”
  10. After adding it, you must wait until your app is updated and refreshed, then you are going to be able to see into the jar you just pasted on the folder lib.
  11. Now it is time to customize you GUI before coding this example using the USB-serial Library.
  12. So expand the folder “src”, which is located within the folder “app”, and find the GUI layout which is located on “/src/main/res/layout” as you can see in the following image.

    then double click on the activity layout, and your Android Studio’s perspective will be changed to:
  13. Now it is time to add a button, so select from the palette the widget “Button”, and drag and drop it on the cellphone’s screen.


  14. Rename it with the name “Send” on properties, and change its ID name as well with “btSend”



  15. Now go to the view “component tree” and remove the TextView is in there.

  16. Now, search on the palette, under TextFields, the option “Plain Text”, and add 2 of those into the layout.

    Locate one of them above the button btSend, and the other one below the button btSend

  17. The one above the btSend, change its id by the name “txText”.
  18. The second textField id, change it to “rxText”
  19. Now we have a basic layout to start coding.
  20. Now double click on the java “Fpgalover_USB_Serial.java” which is under the main folder into the java folder.
  21. There should be a basic code like the following


  22. Now download the following java files, and paste them on the same folder in which is located “Fpgalover_USB_Serial.java”


  23. Now, we have to add the following lines at the top of the file “Fpgalover_USB_Serial.java” in order to add the pasted java files to our Android program, and in addition we need to add some extras libraries just to facilitate the coding.


  24. Once, you have added the import lines, we must add one last line before start coding this useful example. Under the main project’s folder, there is a file called “AndroidManifest.xml”, double click on it to open it, and add the following line to give the feature of accessing to the USB hardware to our Android app.


  25. Go back to our main java code, and let’s start coding our app, first add the following variables to our main code.


  26. Now within the event “OnCreate”, add the following lines, which initialize the widgets, and add the event on Click to the button btSend.

    so, every time you press on the button btSend, the app will take the text of the rxText widget and send it through the USB-Serial Channel.

  27. Now, we have to implement the USBSerialListener into our main code and override it. For that, modify our main class appending the line “implements USBSerialListener”


  28. An apparent error seems to have come up, however you have nothing to worry about, this happens because we haven’t overridden any of the function of the USBSerialListener into our main class.


  29. To solve this, you must copy the following lines into our class.


  30. Once the error has been solved, we have to code and override each of the functions of our USB-Serial Listener. Starting with the method “OnDataReceived”, so what we want every time we get data from our serial port will be to put it into our rxText field, for that we must add the following lines into the method.


    So, id the incoming data is different from null, we put on our textfield, the received data in HEX format and string format.

  31. Now, on the even every time we get and error when receiving data, we are going to use the android Toast to pop up a message on the screen telling we have captured an error.
  32. When our phone has acknowledged that the USB-serial device has been recognized, we modify the method “OnDeviceReady” to enable the widgets on our app.


  33. When the USB-serial is disconnected from our cellphone, we modify the method “OnDeviceDisconnected” to show on the screen the event.
  34. Now, we have just one final thing to do before building our app and test it. We need to add 2 more events into our class, the event “OnResume()”, and “OnPause()”. OnResume() will open the USB-serial channel at 115200 by default, and OnPause() will pause the com channel.


  35. Finally, we can build our app, by clicking on the menu “Build->Make Project”


  36. If everything turns out well you will have no errors on your app, if not you can check on the code as guidance (Download from here).
    package com.fpgalover.fpgalover_usb_serial;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    
    //few android libraries
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.Toast;
    
    //the USB-serial Libraries
    import com.fpgalover.fpgalover_usb_serial.ResponseStatus;
    import com.fpgalover.fpgalover_usb_serial.USBSerialConnector;
    import com.fpgalover.fpgalover_usb_serial.USBSerialListener;
    import com.fpgalover.fpgalover_usb_serial.Utilities;
    
    
    public class Fpgalover_USB_Serial extends AppCompatActivity implements USBSerialListener {
    
        USBSerialConnector mConnector;// USB-serial library class
        EditText txTEXT;
        EditText rxTEXT;
        Button btSend;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_fpgalover__usb__serial);
            mConnector = USBSerialConnector.getInstance();
            txTEXT = (EditText) findViewById(R.id.txText);
            rxTEXT = (EditText) findViewById(R.id.rxText);
            btSend = (Button) findViewById(R.id.btSend);
            txTEXT.setEnabled(false);
            rxTEXT.setEnabled(false);
            btSend.setEnabled(false);
    
            btSend.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String data = txTEXT.getText().toString();
                    mConnector.writeAsync(data.getBytes());
                }
            });
    
        }
    
        @Override
        public void onDataReceived(byte[] data) {
            if (data != null) {
                txTEXT.setText(txTEXT.getText()+"\n HEX>"+Utilities.bytesToString(data)+"\nSTRING>"+data);
            } else {
    
            }
        }
    
        @Override
        public void onErrorReceived(String data) {
            Toast.makeText(this, data, Toast.LENGTH_LONG).show();
        }
    
        @Override
        public void onDeviceReady(ResponseStatus responseStatus) {
            txTEXT.setEnabled(true);
            rxTEXT.setEnabled(true);
            btSend.setEnabled(true);
        }
    
        @Override
        public void onDeviceDisconnected() {
            Toast.makeText(this, "Device disconnected", Toast.LENGTH_LONG).show();
            finish();
        }
    
        @Override
        protected void onResume() {
            super.onResume();
            mConnector.setUsbSerialListener(this);
            mConnector.init(this, 115200);
        }
        @Override
        protected void onPause() {
            super.onPause();
            mConnector.pausedActivity();
        }
    
    
    }
    
    ​
  37. It is time to test our app on our phone, for that you must build the APK file and installed it on your cellphone. This can be done by clicking on the menu “Build->Build APK”



  38. Once the APK has been built, and installed on your cellphone, you can test it out by plugging any USB-Serial converter to the OTG port on your cellphone. In this case, I connect a Xbee Xplorer to my phone, and wire up TX and RX to create and echo bridge to be able to echo what I send through the com channel.

    You can Download the whole project form here







Attachments:

 

 

Attachments:
Download this file (usbserial.jar)usbserial.jar[ ]39 kB
Powered by OrdaSoft!
  Written By Peter Gomez Este contenido esta orientado a los programadores que tienen problema con la conectividad("SGC PmmC") de su pantalla uOled-128-g1/g2…
Written by Sherneyko Plata Rangel   Pynq-z2: Hello world   In this tutorial we will implement a simple test of the inputs/outputs available on…
Objetivos Requerimientos Procedimiento Descripción de Hardware. Qsys. Nios II. UCOS II. Secuencia de Sprite. Sintesis de Audio. Descargas Glosario Otros Resultados. Ejemplo de Sprites.     Objetivos: Diseñar una plantilla general para el diseño de…
Written by Holguer A. Becerra           Requerimientos: DE0-NANO USB-UART(solo para parte 3) Python 2.7 ó superior.   Objetivos: Dar una introducción a los conceptos de Multitasking, Scheduling y…
Written by Holguer A. Becerra             Based on Gregory Estrade's Work.   I have ported the PC Engine System on the DE0-NANO back in 2014, why…
      Arduino tools are generally nice tools for quick prototyping and improvized projects, and the Seeeduino Xiao…
Written by: Holguer A Becerra         En esta practica vamos a construir nuestro primer juego retro  usando un sincronizador de Video VGA…
Written by: Andrea Paola Pabón Ortega & Daniel Enrique Mejia Rueda Revision by: Ing Holguer A. Becerra   DESCRIPCIÓN DEL PROYECTO: El  RTAWD DE0NANO…
  Written by Holguer Andres   Requires: DE0-NANO. 4.3 Inch 480x272 Screen.( WQVGA ) ?️       Parte HW: Descargue la siguiente plantilla( DE0_NANO_TFT_PSP.zip) y descomprimala en una ruta sin espacios y…
Escrito por Guillermo Acevedo   Diseño   En esta practica desarrollaremos un filtro FIR en hardware, para este caso en especifico, realizaremos un filtro…
 Written By Juan David Delgado   FILTRO FIR (FILTRO DE RESPUESTA FINITA AL IMPULSO)     Son conocidos como filtros digitales no recursivos debido a…
XISCKER: Reduced and Complex Instruction Set Computing Key Educational Resources A Configurable Platform for the Emulation of Different Computer Architectures An introduction to Computer Architectures through digital design description for FPGA devices   Computer Architecture embraces all three…
Escrito por: Alix Angarita   En el manual a continuación se explica un método de debug adicional que es muy interesante debido a…
By: Fabio Hernández   INTRODUCCIÓN:   El presente documento pretende mostrar la manera de generar software para una imagen de Linux implementada en la…
Summary Written by Fabio Hernandez   HARD PROCESSOR SYSTEM (HPS)     ------------------------------------------------------------------------------------------------------------------------------------------------   Introducción   Tenemos  2 nuclos de procesamiento ARM cortex-A9, cada uno son su propio cache  se…
Escrito por Jesus Lopez         INTRODUCCIÓN   El acceso directo a memoria (DMA, del inglés direct memory access) permite a cierto tipo de componentes de una computadora acceder a…
    Written by  Sebastian Baquero       Objetivos  Introducción a los conceptos de Multitasking, Scheduling y Context Switching.  Ampliación de los conceptos a cerca de el…