Saturday, March 8, 2014

Two way communication between Arduino and Android

In last post i have showed you how to communicate two Arduino Uno using Bluetooth(RN-42). 
                                                             Now in this post i will show you how to connect Arduino Uno with Android phone using Bluetooth.


Before going further i will discuss some basic API's that we will be using in our android Programming. 

In this post we will show how to use Android Bluetooth classes and we will explore some of the Bluetooth API's that is used to develop this Android Bluetooth Application. These API's let your device to connect with other Bluetooth devices enabling point - to- point and Multipoint wireless features.



Using this Bluetooth API's an android application can scan other Bluetooth Devices present nearby, can pair with other Bluetooth devices, can establish RFCOMM, can transfer and receive data and can even manage multiple Bluetooth connections.



All these API's are available in android:bluetooth package. Now we will discuss some of the classes and Interfaces required for Bluetooth connection. (Taken from developer.android.com)



1. BluetoothAdapter- This Class helps to perform some of the basic tasks like initiate device discovery


2. BluetoothDevice - It is used to request for connection with remote device through a Bluetooth socket. It also query about the device name, class, bonding state, etc.

3. BluetoothSocket - It allow an application to exchange data through input and output stream.

4.BluetoothServerSocket - It is a open socket that listen to the incoming request. In order to connect to android devices one device must open as a server socket with this class. whenever a remote device request for a connection to this device, the BluetoothServerSocket will return a connected BluetoothSocket when the connection is excepted. 

5. BluetoothClass - Describes the general characteristics and capabilities of a Bluetooth Device. It is read only set of properties that define the device's major and minor classes and its services.

 Now CREATE a android Bluetooth application and name it as Bluetoothapp

Bluetooth Permission:-
 
Now go to the android Manifest file and give permission to your application so that it can use the Bluetooth features. If you don't give Permission your Bluetooth application won't be able to use the Bluetooth features.

android:name="android.permission.BLUETOOTH" />

This permission is required to perform any Bluetooth communication such as 
requesting connection, accepting a connection and transferring data. 
 
android:name="android.permission.BLUETOOTH_ADMIN" />

If the application need to initiate device discovery and if it needs to change the settings of the Bluetooth then the above permission is required.


Bluetooth Setting:-  

 Before our application can communicate over Bluetooth we should check weather the device have Bluetooth support. If the device have Bluetooth the we will check weather the Bluetooth is already enabled or it is disabled.

BluetoothAdaper is required for any or all Bluetooth Activity. To get BluetoothAdapter call
getDefaultAdapter() method. There is only one BluetoothAdapter for whole system 
and your application will interact with this using this object. 
                                           If .getDefaultAdapter() returns null then 
device doesn't support Bluetooth and if returns non null values then we will check 
weather the Bluetooth present in the device is already enabled or not.
                                             If the Bluetooth is already enabled the it will prompt 
the user that the Bluetooth is already Enabled and if the Bluetooth is Disabled then we 
will request for StartActivityForResult() with the ACTION_REQUEST_ENABLE action 
Intent which will Enable the Bluetooth. 



1:   private BluetoothAdapter bluetoothAdapter = null;   
2:   bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();// used to check weather the device support Bluetooth or not.  
3:   if(bluetoothAdapter!=null) {   
4:                // if .getdefaultAdapter return non null values it means Bluetooth is supported in the device  
5:       if (! bluetoothAdapter.isEnabled()) {  
6:                // Prompt the user that Bluetooth is Disabled  
7:             Intent enablebluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);  
8:             startActivityForResult(enablebluetooth, REQUEST_ENABLE_BT);  
9:       }  
10:       else  
11:       {  
12:                //Promt the user that Bluetooth is already Enabled  
13:       }  
14:      }   
15:   else '  
16:    {  
17:     // Bluetooth is not supported and hence the application should exit     
18:    }  



Managing a connection:-  

The connection Thread is a inner class, it passes the message to the handler which carries out the required action.




The InputStream and OutputStream that handle transmission through the 

socket via getInputStream and getOutputStream respectively.


In this class we have two method one is read and other is write. whenever we will 

send some data it will be send to the outputStream and the Bluetooth will send it 
to the target device and when the data is received through InputStream in read methord, this methord send the data to the main activity using a member handler from the parent class. Then it goes and waits for more bytes from the input stream. 



The above code shows how the write method is used to send data to output stream.
We have created a Thread in our program which will handle the incoming data  and it send the data to the handler where the messages are kept in queue so that it can be 
executed latter. The handler object register itself with the thread in which it is created.

The main reason behind creating a Thread are:-
If we write all the method and and inner-classes inside the main Thread also known as UI Thread then a situation may arrive where out application may not respond or may get forced close. The reason is if we are writing and reading the data at the same time then deadlock occurs and the application doesn't respond. So to avoid this we have written a Thread which will handle the incoming data.
So Public void run() the thread which will handle the incoming data and it will send these byte array to the Handler which is written in the main UI Thread.

Handler:-

Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.

The main uses of Handler are:-
1. To schedule messages that can be executed as some point in the future.
2. To Enqueue an action to be performed on a different Thread.



In this handler the Byte array is converted to string and then by using endOfLineIndex we check the End of Data and that information that is received is displayed on the Text Box.
In the Text field the Incoming data will be displayed when ever the ON button is pressed.
when we press ON button "1" is send to the Arduino board and when the OFF button is pressed "0" is send. 

The link to this code is given below.

https://www.dropbox.com/s/4xskroj5pyf8jta/Bluetooth2.rar





NOW WE WILL SHOW HOW TO CONNECT YOUR SENSOR WITH THE ARDUINO BOARD.


As a sensor we have used Flexi Force sensors but any sensor can be connected with Arduino and the values can be obtained in your Android phone.

Connect the Bluetooth RN-42 and Sensor With the Arduino Uno as shown.

The link for Arduino Uno code is given Below:

In this code when the Arduino receives "1" from the serial comm it starts reading the analog pin A0 and then the ADC values is send back to Android phone.
and when it receives "0" its stop reading the analog pin A0

No comments:

Post a Comment