Arduino----OTG----Android

Connect sensors and electronics controlled by microcontrollers with arduino enabled programming and communicated through OTG USB cables or BT or other serial or wifi communication systems with Adroid OS and custom Apps made with Android dev app.

Download and setup Android Studio to create custom apps
  1.  version Get the android studio from http://developer.android.com/sdk/index.html

    => download an exe file of size  around 1gb

  2. Installing Android Studio

    At the end it will install latest SDK version automatically (takes time wait for it).
    You should end up getting to the welcome screen of android studio.

  3. Setting Up Android Studio

    Click the configure button, to go to the configuration page.
    Here the first option would be to use the “SDK Manager”, and open a window showing the details of current SDK. There select “launch standalone SDK Manager“, then a SDK manager will be opened where you can add new SDK tool as required.

    Android studio has an emulator to test the android code, but we cannot use that for this scenario  involving a physical device talking to another device. We need to use the android phone or computer itself to plug the USB OTG and  debug the code.

    As we use an android device to debug the code we can just download “SDK Platform” of that specific version of the device used, so we first need to know the android OS version on the device.
    In my case I am using
    -For eample, if using a Samsung note3 with android 5.0 (lollipop) you need to download “SDK Platform” from “Android 5.0.1 (API 21)” at least (i.e. as oldest).

creating a new project : case arduino-otg-app

. 1) Clic on “Start a new android studio project” from the welcome window
2) give your project name and location, then click next
3) select the platform for which we are developing application and select the version of your phone OS and click next
4) first leave th default “Blank activity” as selected for now and clic next.
5) Finaly, name your activity ( i.e.  your main screen in the app).
6) click finish. A newly created project will be opened in android studio and we can work with it now

 

Adding external libraries (.jar) to an Android studio project

 

 

Application case: open the hysicaloid library for USB communication management between Arduino and Android.

Source Tuto: https://www.instructables.com/Arduin-Adroid-USB-Serial-Communication/

 Source librairie: https://content.instructables.com/FNM/9MXQ/IJUCPKBD/FNM9MXQIJUCPKBD.jar

 

1) In the top left side of the main screen there will be a drop down menu labelled 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 find lib folder that is the default folder to place our libraries.

2) Copy the physicaloidlibrary.jar file and paste it in libs folder

3) After pasting click “sync project with gradle files” 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 first 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

Editing the manifest file of a new project

Editing the manifest file of a new project:

Manifest file is like main properties file for our project, It contains permissions details and activity details

Manifest file is located in App > src > main > AndroidManifest.xml

Open the file and add

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

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

 

 

The manifest file example will then  looks like:

<?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>

 

Designing a new layout: case of the arduino serial monitor reproduction

Designing a new layout: case of the arduino serial monitor reproduction:

Editing should be done in “content_serial_monitor.xml” file

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 file 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>

OPTION: Add CUSTOM ICON to our app

right click on the app > new > image asset

now browse the image file you want and set it as ic_launcher it will override the default android icon

Source Code example: https://content.instructables.com/F8L/F5P8/IJUCQ87O/F8LF5P8IJUCQ87O.xml

Adding Code to UI Elements

 Adding Code to UI Elements:

Here is  the complete java file Serial_monitor.java first download it and compare it to these small code segments.
https://content.instructables.com/F3T/71R7/IJUCQVC1/F3T71R7IJUCQVC1.java

Below are detailled description of the code:

First are  created all  UI elements and library variables

    Button btOpen, btClose,  btWrite;
    EditText etWrite;
    TextView tvRead;
    Spinner spBaud;
    CheckBox cbAutoscroll;

    Physicaloid mPhysicaloid; 		// initialising library

Second, 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 context for library

Now we can display Required UI elements on screen, calling a method to do this

That method takes boolean argument which specifies 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 opened)
            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 needed, and 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.

 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);
                break;
            case "576600 baud":
                mPhysicaloid.setBaudrate(576600);
                break;
            case "744880 baud":
                mPhysicaloid.setBaudrate(744880);
                break;
            case "115200 baud":
                mPhysicaloid.setBaudrate(115200);
                break;
            case "230400 baud":
                mPhysicaloid.setBaudrate(230400);
                break;
            case "250000 baud":
                mPhysicaloid.setBaudrate(250000);
                break;
            default: 		// default is 9600
                mPhysicaloid.setBaudrate(9600);
        }

        if(mPhysicaloid.open()) { 	// tries to connect to device and if device was connected
            setEnabledUi(true);

            if(cbAutoscroll.isChecked()) { 	// if auto scroll was selected
                tvRead.setMovementMethod(new ScrollingMovementMethod());
            }   

	   // read listener, When new data is received from Arduino add it to Text view
            mPhysicaloid.addReadListener(new ReadLisener() {
                @Override
                public void onRead(int size) {
                    byte[] buf = new byte[size];
                    mPhysicaloid.read(buf, size);
                    tvAppend(tvRead, Html.fromHtml("<font color=blue>" + new String(buf) + "</font>"));// add data to text viiew
                }
            });

        } else {
		//Error while connecting
            	Toast.makeText(this, "Cannot open", Toast.LENGTH_LONG).show();
        }
    }

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 array
            mPhysicaloid.write(buf, buf.length);	//write data to arduino
        }
    }

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

Attachments