Harness the power of Bluetooth to communicate with your Arduino!

This is part two of a series, which will focus on using Bluetooth to communicate with an Arduino. Bluetooth is one of the popular wireless communication technologies because of its low power consumption, low cost and a light stack but compensates on range. 

 

Requirements

  • An Arduino
    Any model of the Arduino can be used, but all code and schematics in this article will be for the Uno.
  • An Android Smartphone with Bluetooth
    Check if your phone has Bluetooth by navigating to "Wireless and Networks" under settings.

  • HC-05 Bluetooth Module
    This module is the most popular Bluetooth module out there. The basic version is pretty inexpensive. The hassle of having to connect wires between the module and the Arduino can be avoided by using a Bluetooth Shield or a version in the Bee shape, the BTBee  and a Bee shield.

  • Android Studio

  • USB cable for the Arduino

 

Setting Up the Hardware

To use the HC05 module, simply connect the VCC to the 5V output on the Arduino, GND to Ground, RX to TX pin of the Arduino, and vice versa. If you are using the BTBee module with the shield, set the jumpers on the board so that the DOUT pin and D0 pins are shorted and DIN and D1 pins are shorted. This is done because the RX pin on the Arduino is Pin 0 and the TX pin is Pin 1. You are free to use any other pins as the RX and TX Pins, but you will have to use the SoftwareSerial Library of the Arduino to enable that. Do remember to remove the jumpers while uploading code to the Arduino if you have selected Pin 0 and 1 as Serial pins. 

Connecting the HC05 Module

Jumper connected to Pins 0 and 1 on the BTBee shield

If the module is being used for the first time, you'll want to change the name, passcode etc. To do this the module should be set to command mode. Connect the Key pin to any pin on the Arduino and set it to high to allow the module to be programmed. If you're using the BTBee, it's a little tricky. While the official wiki says that the Mode Button must be held to change it to Command Mode, and releasing it changes it back to Data Mode, it doesn't happen that way: instead, hold the Mode button, then quickly press and release the Reset button. You will notice that the Status LED blinks slower than usual.

To program the module, a set of commands known as AT commands are used. Here are some of them:

AT Check connection status.
AT+NAME ="ModuleName" Set a name for the device
AT+ADDR Check MAC Address
AT+UART Check Baudrate
AT+UART="9600" Sets Baudrate to 9600
AT+PSWD Check Default Passcode
AT+PSWD="1234" Sets Passcode to 1234

All the set commands return "OK" when they are executed successfully.

Here's some code to change the name. The jumpers are connected to 4 and 5 because the response from the module will be printed on the Serial Monitor. The complete code is available at the end of this article in the "download code" button. 

 

                    //If youre not using a BTBee connect set the pin connected to the KEY pin high
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(4,5); 
void setup() {
  String setName = String("AT+NAME=MyBTBee\r\n"); //Setting name as 'MyBTBee'
  Serial.begin(9600);
  BTSerial.begin(38400);
  BTSerial.print("AT\r\n"); //Check Status
  delay(500);
  while (BTSerial.available()) {
      Serial.write(BTSerial.read());
    }
  BTSerial.print(setName); //Send Command to change the name
  delay(500);
  while (BTSerial.available()) {
      Serial.write(BTSerial.read());
    }}
void loop() {}
                  

Programming the Arduino

No extra library is used to connect to the Bluetooth module because the RX and TX pins of the Arduino are shorted with those of the module. All data--outgoing and incoming--will have to go through the module. Interfacing the module is that easy.
To see how this works, let us connect a DHT-11 Temperature Sensor to the Arduino. When the letter "t" is received, the temperature, humidity, and heat index will be transmitted back. To use the DHT-11, the DHT library by Adafruit is used.

The Shield and the connected DHT Sensor

Below is the code used to read data from the DHT sensor, process it, and send it via Bluetooth.

 

                    #include "DHT.h"
#define DHTPIN 2     
#define DHTTYPE DHT11  
DHT dht(DHTPIN, DHTTYPE);
void setup() {
  Serial.begin(9600);
  dht.begin();}

void loop()
{  char c; 
if(Serial.available())  
  {  
   c = Serial.read();  
   if(c=='t')
   readSensor();
  }}
void readSensor() {
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  float hic = dht.computeHeatIndex(t, h, false);
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" *C ");
  Serial.print("Heat index: ");
  Serial.print(hic);
  Serial.print(" *C ");
}
                  

The Android App

Take a look at the previous article for a quick intro about Android apps and also the layout for this app.

The program flow will be as illustrated above.

 

Editing AndroidManifest.xml

Since the extra hardware this app will be using is the onboard Bluetooth adapter, it will have to be mentioned in the Manifest.

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

 

Connecting to the Device

First check for the presence of a Bluetooth Adapter.

        BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();

        if (bluetoothAdapter == null) {

            Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();

        }

 

If it is present, check if it's enabled. If it isn't enabled, ask the user permission to enable it.

if(!bluetoothAdapter.isEnabled())

        {

            Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

            startActivityForResult(enableAdapter, 0);

        }

The device must be paired before the app can use it. Check the section below for details on how to pair the BT Module and the Phone. Now that the adapter is enabled, check for paired/bonded devices. Using the AT Commands from the section above, give an appropriate name to the device. Also find out its MAC Address. Here, the MAC addresses are being compared for a match because names are liable to be changed often.

Set bondedDevices = bluetoothAdapter.getBondedDevices();

if(bondedDevices.isEmpty()) {

     Toast.makeText(getApplicationContext(),"Please Pair the Device first",Toast.LENGTH_SHORT).show();

} else {

     for (BluetoothDevice iterator : bondedDevices) {

          if(iterator.getAddress().equals(DEVICE_ADDRESS)) //Replace with iterator.getName() if comparing Device names.

          {

             device=iterator; //device is an object of type BluetoothDevice            

             found=true;            

             break;

          } } } 

After getting the BluetoothDevice, a socket has to be created to handle the outgoing connection. Here a RFCOMM socket is used. RFCOMM--also known as Serial Port Profile--is essentially a Bluetooth protocol to emulate an RS232 cable. ​

socket = device.createRfcommSocketToServiceRecord(PORT_UUID); socket.connect();

Then get the input and output streams of the socket.

outputStream=socket.getOutputStream();

inputStream=socket.getInputStream();

 

Reading Incoming Data

Since data can be received at any point of time, running a thread to listen for data would be best. First, the input stream is queried for available data. Then, the bytes are converted to human readable UTF-8 format and the text is send to a handler to post onto the UI. This is done because the UI can't be updated from background threads.

        int byteCount = inputStream.available();
        if(byteCount > 0)
         {
            byte[] rawBytes = new byte[byteCount];
            inputStream.read(rawBytes);
            final String string=new String(rawBytes,"UTF-8");
            handler.post(new Runnable() {
                    public void run()
                    {
                        textView.append(string);
                    }
            });
          }

 

Transmitting Data

To send data, pass the String to the OutputStream.

outputStream.write(string.getBytes());

 

Download the Source Code for the App

  Download Code  


Testing the App

First off, pair the phone and the module by scanning for new devices in the Bluetooth tab of the System Settings. The name which was set earlier should appear. Put in the set passcode (Default is either 0000 or 1234).

After you power on the Arduino, you may notice that the BTBee's status LED blinks periodically. Now open the app and tap Begin. The status LED must go off and the Conn LED will glow. This shows that a connection has been established.

When "t" is sent to the Arduino, it replies with the Temperature, Humidity, and Heat Index.

That was a simple exhibition of data transfer using Bluetooth. Bluetooth can be used to control the automation of many everyday things, like switching a lightbulb on, which can be done by using a Relay with the Arduino. This concludes this two-part series on interfacing an Arduino with an Android phone. The first part on using a Serial Cable can be found here.

 

Comments

8 Comments


  • briantee 2016-03-07

    When i try to compile app its gradle says:

    Error:(1, 0) Plugin with id ‘com.android.application’ not found.
    Open File

    • @briantee: just upgrade to appcombat, gradle to lastest version. It’s work fine

      buildscript {
      repositories {
      jcenter() // or mavenCentral()
      }

        dependencies {
      classpath 'com.android.tools.build:gradle:2.2.1'
      }
      }

      dependencies {
      compile fileTree(dir: 'libs', include: ['*.jar'])
      compile 'com.android.support:appcompat-v7:25.0.0'
      }

  • fredy67 2016-03-24

    hi, I had this same error,,add the following code to the top of your gradle build, that must solve the problem

    buildscript {
    repositories {
    jcenter() // or mavenCentral()
    }

      dependencies {
    classpath 'com.android.tools.build:gradle:1.5.0'
    }
    }

  • Rimish Bansod 2016-04-05

    Can we use simple board instead of arduino board with same bluetooth module and android app ?
    Here in android app, we have to enter mac id of Bluetooth module manually in code.
    Instead of entering manually, how to select bluetooth module from list of available device and then fetch its mac id and then connect

  • _Rich 2016-08-18

    I tried this recently and have the USB OTG (part 1) working fine - I needed to remove the check for the Arduino vendorID (a bit unsecure, but hey it wasn’t accepting the listed vendorID or any variation thereof).

    When I came to use the Bluetooth version, the app would do nothing when the begin button was pressed. I strongly suspect it is because the permissions have changed in Android 6. Here is a potential answer on Stackoverflow that provides some more details:
    http://stackoverflow.com/questions/33142034/android-6-bluetooth

  • Bioluminobay 2016-08-24

    Hi Hariharan,
    If you were to program an app that interacts with the arduino, what language would you use?