Wednesday 29 April 2015

Bluetooth communication between Arduino and Android

      Communication between Arduino and Android might seem scary and troublesome at first when you start to get errors in communicating and you don’t find where exactly the problem lies. Believe me it’s lot simpler than it looks. The only thing required is a proper guidance. While doing it on my own I have had many problems and would want others not to face the similar problems. 

      So here in this post I will be controlling a LED light that is connected to the Arduino board from an Android device via Bluetooth.

The hardware requirements are:

      1)      Arduino Uno  
      2)      Bluetooth Module (Example: HC-05) 
      3)      An Android Device (Example: Samsung Galaxy)  
      4)      A LED Light

Once these devices are available the connections that need to be made are as shown in the following fig:


Connect the anode pin of LED light to the Pin12 and cathode pin to the GND Pin of Arduino.

                                                  
The JY-MCU module (Bluetooth module) communicates with the Arduino via a serial connection. The 4 pins that we will be using are:
  • VCC => used to power the module. It needs to be connected to the Arduino 5V pin
  • GND => the ground pin. It needs to be connected to the Arduino GND pin
  • TXD => used to send data from the Bluetooth module to the Arduino. It needs to be connected to the  receive pin (RXD) of the Arduino, which in our case is pin 6 on the UNO.
  • RXD => used to receive data from the Arduino. It needs to be connected to the the Arduino transmit pin (TXD), which in our case is pin 7 of Arduino Uno.
  • We will not be using the “STATE” and the “KEY” pins of the Bluetooth module, so they need not be connected.

Once these connections are done, we have to code the Arduino UNO to accept Bluetooth serial data and make 
the LED ON or OFF depending on the input byte.

To start with, first download the Arduino IDE by visiting the following link:

Then connect the Arduino UNO board to your computer via the USB cable and open the Arduino IDE by clicking on the .exe file that you’ve just downloaded. Then copy the following code to your IDE and save it. Then click the upload button to build, compile and upload the code to your android UNO board. Once the compilation is successful your Arduino board is ready to receive the data.
The arduino code is fairly simple.
  • It establishes a serial connection between the Arduino and the Bluetooth module
  • RXD(Pin 6) and TXD(Pin 7) Arduino pins communicate with the TXD and RXD pins of the module
  • Listen for input on the serial port 12 and process it
  • Turn the LED on pin 12 ON, if it reads 1 (one) as serial input
  • Turn the LED on pin 12 OFF, if it reads 0 (zero) as serial input

Arduino code

#include <SoftwareSerial.h>     //Software Serial Port
#define RxD 6        // This is the pin that the Bluetooth (BT_TX) will transmit to the Arduino (RxD)
#define TxD 7        // This is the pin that the Bluetooth (BT_RX) will receive from the Arduino (TxD)

SoftwareSerial blueToothSerial(RxD,TxD);
char incomingByte;  // incoming data
int  LED = 12;      // LED pin

void setup() {
 Serial.begin(9600);          // Allow Serial communication via USB cable to computer (if required)
pinMode(RxD, INPUT);    // Setup the Arduino to receive INPUT from the bluetooth shield on Digital               Pin 6
pinMode(TxD, OUTPUT);  // Setup the Arduino to send data (OUTPUT) to the bluetooth shield on Digital Pin 7
pinMode(LED, OUTPUT);
setupBlueToothConnection();
}

void loop()
{  
   if(blueToothSerial.available())     // If the bluetooth is connected and sent any characters
  {
        incomingByte = (char)blueToothSerial.read();            // read byte
        if( incomingByte == '0' )
        {
               digitalWrite(LED, LOW);                                          // if 0, switch LED Off
       }
      if( incomingByte == '1' )
      {
          digitalWrite(LED, HIGH);                                  // if 1, switch LED ON
      }
  }
}

void setupBlueToothConnection()
{
   //Setup Bluetooth serial connection to android
  blueToothSerial.begin(115200);
  blueToothSerial.print("$$$");
  delay(100);
  blueToothSerial.println("U,9600,N");
  blueToothSerial.begin(9600);
 }

Next create a new Android project in Eclipse and copy the following code into your MainActivity.java file:

MainActivity.java

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class ConnectArduino extends Activity{           
    BluetoothAdapter mBluetoothAdapter;
    BluetoothSocket mmSocket;
    BluetoothDevice mmDevice;
    OutputStream mmOutputStream;
    InputStream mmInputStream;
   
    TextView status;
    Button connect;
    Button disconnect;
    Button turn_LED_ON;
    Button turn_LED_OFF;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                        // TODO Auto-generated method stub
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.activity_main);
                        connect = (Button)findViewById(R.id.connect);
                        disconnect = (Button)findViewById(R.id.disconnect);
                        turn_LED_ON = (Button)findViewById(R.id.on);
                        turn_LED_OFF = (Button)findViewById(R.id.off);
                        status = (TextView)findViewById(R.id.status);
                        status.setText(“Bluetooth Disconnected”);
                        disconnect.setEnabled(false);
                        turn_LED_ON.setEnabled(false);
                        turn_LED_OFF.setEnabled(false);                   

connect.setOnClickListener(new View.OnClickListener()
                     {
                         public void onClick(View v)
                         {     
                        try
                                    {
                                    findBT();
                                    }
                           catch (IOException ex) { }
}
                     }); 
                        disconnect.setOnClickListener(new View.OnClickListener()
                     {
                         public void onClick(View v)
                         {     
                        try
                                    {
                                    closeBT();
                                    }
                           catch (IOException ex) { }
}
                     }); 
                        Turn_LED_ON.setOnClickListener(new View.OnClickListener()
                     {
                         public void onClick(View v)
                         {     
                        try
                                    {
                                    sendData(“1”);
                                    }
                           catch (IOException ex) { }
}
                     }); 
                        Turn_LED_OFF.setOnClickListener(new View.OnClickListener()
                     {
                         public void onClick(View v)
                         {     
                        try
                                    {
                                    sendData(“0”);
                                    }
                           catch (IOException ex) { }
}
                     }); 
}

void findBT() throws IOException
    {
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter == null)
        {
            status.setText("No bluetooth adapter available");
        }
        if(!mBluetoothAdapter.isEnabled())
        {
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
        mmDevice = mBluetoothAdapter.getRemoteDevice("20:13:09:23:00:48");
         //”20:13:09:23:00:48” is the MAC address of the Bluetooth module
        if (pairedDevices.contains(mmDevice))
        {
             status.setText("Bluetooth Device Found, address: " + mmDevice.getAddress() );
                Log.d("ArduinoBT", "BT is paired");
        } 
      
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
        mmSocket = mmDevice.createInsecureRfcommSocketToServiceRecord(uuid);
        Method m = mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
        mmSocket = (BluetoothSocket) m.invoke(mmDevice, 1);
        mBluetoothAdapter.cancelDiscovery();
        mmSocket.connect();       
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();

        status.setText("Bluetooth Connected");
        connect.setEnabled(false);
        disconnect.setEnabled(true);
        turn_LED_ON.setEnabled(true);
        turn_LED_OFF.setEnabled(true); 
}
void sendData(String m) throws IOException
 {
mmOutputStream.write(m.getBytes());
}
void closeBT() throws IOException
{                  
mmOutputStream.close();
mmInputStream.close();
            mmSocket.close();
            status.setText("Bluetooth Disconnected");
              connect.setEnabled(true);
              disconnect.setEnabled(false);
              turn_LED_ON.setEnabled(false);
              turn_LED_OFF.setEnabled(false);      
}
}

In your activity_main.xml file create four buttons for connect, disconnect, turn_LED_ON, turn_LED_OFF operations and a TextView to display the status of the Bluetooth.


Also, include the following uses-permission in your AndroidManifest.xml file
<uses-permission android:name=”android.permission.BLUETOOTH” />

NOTETo find out the MAC address of your Bluetooth module you need to connect your module to PC and then click on the device’s properties window. You can then read the MAC address of your module from the properties window.


Hope this information was useful. If you have any doubts or you’re still encountering any errors just leave a comment and I will try my best to help you out. Keep reading! J




No comments:

Post a Comment