All about HC-05 Bluetooth Module | Connection with Android

Ever wanted to control your Mechanical Bots with an Android Phone or design the robots with custom remote, here in this tutorial we will learn about a Bluetooth Module HC-05 used for the above mentioned and many other cases. Here we will be understanding the connection and working of a HC-05 module and also its interfacing with custom android app.
Basics
Wireless communication is swiftly replacing the wired connection when it comes to electronics and communication. Designed to replace cable connections HC-05 uses serial communication to communicate with the electronics. Usually, it is used to connect small devices like mobile phones using a short-range wireless connection to exchange files. It uses the 2.45GHz frequency band. The transfer rate of the data can vary up to 1Mbps and is in range of 10 meters.
The HC-05 module can be operated within 4-6V of power supply. It supports baud rate of 9600, 19200, 38400, 57600, etc. Most importantly it can be operated in Master-Slave mode which means it will neither send or receive data from external sources.

HC-05 module

Description of pins

  • Enable - This pin is used to set the Data Mode or and AT command mode (set high).
  • VCC - This is connected to +5V power supply.
  • Ground - Connected to ground of powering system.
  • Tx (Transmitter) - This pin transmits the received data Serially.
  • Rx (Receiver) - Used for broadcasting data serially over bluetooth.
  • State -Used to check if the bluetooth is working properly.

Modes of Operation

The HC-05 Bluetooth Module can be used in two modes of operation: Command Mode and Data Mode.

Command Mode

In Command Mode, you can communicate with the Bluetooth module through AT Commands for configuring various settings and parameters of the Module like get the firmware information, changing Baud Rate, changing module name, it can be used to set it as master or slave.

A point about HC-05 Module is that it can be configured as Master or Slave in a communication pair. In order to select either of the modes, you need to activate the Command Mode and sent appropriate AT Commands.

Data Mode

Coming to the Data Mode, in this mode, the module is used for communicating with other Bluetooth device i.e. data transfer happens in this mode.



Programming HC-05 with Microcontroller

Technical specs of the code:

  • Arduino-Uno is used as the microcontroller.
  • Name: HC-05
  • Password: 1234 (or 0000)
  • Type: Slave
  • Mode: Data
  • Baud Rate: 9600 with 8 data bits, no parity and 1 stop bit
filter_none

edit
close

play_arrow

link
brightness_4
code

//Define the variable that contains the led
#define ledPin 7
int state = 0;
void setup() {
  //Setting the pin mode and initial LOW 
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  Serial.begin(9600); // Default communication rate
}
void loop() {
  // Checks if the data is coming from the serial port
  if(Serial.available() > 0){ 
    state = Serial.read(); // Read the data from the serial port
 }
 Deciding functions for LED on and off 
 if (state == '0') {
  digitalWrite(ledPin, LOW); // Turn LED OFF
  // Send back, to the phone, the String "LED: ON"
  Serial.println("LED: OFF"); 
  state = 0;
 }
 else if (state == '1') {
  digitalWrite(ledPin, HIGH);
  Serial.println("LED: ON");;
  state = 0;
 
}

chevron_right


Android App interfacing with HC-05

Now, we will develop a small android application to demonstrate the connection of bluetooth module and the android app. We will be using Android Studio for this purpose and above mentioned C code on the microcontroller.

Algorithm:

  1. Create an empty project on Android Studio
  2. Create a ListView containing all the available bluetooth devices.
  3. Get the name and MAC-address of HC-05 module.
  4. Open connection with HC-05 module.
  5. Instruct the module with data as bytes.

Understanding the code

1.Getting all the Bluetooth devices in ListView

This code is for the MainActivity or first activity where the list will be displayed then after that when device will be selected, Control activity will come to give the command.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Initializing the Adapter for bluetooth
private BluetoothAdapter BluetoothAdap = null;
private Set Devices;
// comes in Oncreate method of the activity
BluetoothAdap = BluetoothAdapter.getDefaultAdapter();
  
// Method to fill the listwith devices
private void pairedDevices()
{
    Devices = BluetoothAdap.getBondedDevices();
    ArrayList list = new ArrayList();
  
    if (Devices.size() > 0) {
        for (BluetoothDevice bt : Devices) {
            // Add all the available devices to the list
            list.add(bt.getName() + "\n" + bt.getAddress());
        }
    }
    else {
        // In case no device is found
        Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
    }
  
    // Adding the devices to the list with ArrayAdapter class
    final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, list);
    devicelist.setAdapter(adapter);
  
    // Method called when the device from the list is clicked
    devicelist.setOnItemClickListener(myListListener);
}

chevron_right


2.Getting the name and MAC address of device

Now we will create a OnClick Listener for the list so that thename and MAC address can be extracted from the device.

filter_none

edit
close

play_arrow

link
brightness_4
code

// On click listener for the Listview
private AdapterView.OnItemClickListener myListListener = new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView av, View v, int arg2, long arg3)
    {
        // Get the device MAC address
        String name = ((TextView)v).getText().toString();
        String address = info.substring(info.length() - 17);
  
        // Make an intent to start next activity.
        Intent i = new Intent(MainActivity.this, Control.class);
        // Put the data got from device to the intent
        i.putExtra("add", address); // this will be received at control Activity
        startActivity(i);
    }
};

chevron_right


3.Establishing a connection between both of them

The connect() function in the Control.java will help to make the connection between both.

filter_none

edit
close

play_arrow

link
brightness_4
code

BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
// This UUID is unique and fix id for this device
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  
// receive the address of the bluetooth device
Intent intent = getIntent();
address = intent.getStringExtra("add");
  
try {
    if (btSocket == null || !isBtConnected) {
        myBluetooth = BluetoothAdapter.getDefaultAdapter();
  
        // This will connect the device with address as passed
        BluetoothDevice hc = myBluetooth.getRemoteDevice(address);
        btSocket = hc.createInsecureRfcommSocketToServiceRecord(myUUID);
        BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
  
        Now you will start the connection
            btSocket.connect();
    }
}
catch (IOException e) {
    e.printStackTrace();
}

chevron_right


4.Finally commanding the HC-05 module

Here first we will check if our socket is connected, then only we will proceed to avoid the Null Pointer exception.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Function for commanding the module
private void turnOffLed()
{
    if (btSocket != null) {
        try { // Converting the string to bytes for transferring
            btSocket.getOutputStream().write("0".toString().getBytes());
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

chevron_right


Now finally as we have done our first basic project with the HC-05 module and the Android programming, we can move on to complex electronic bots and make there wired connection to wireless using this amazing module HC-05 and also we now know to make a custom app.

You can find the above code in form of Android Studio Project commited here.

Attention reader! Don’t stop learning now. Get hold of all the important CS Theory concepts for SDE interviews with the CS Theory Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

A computer Vision and Machine Learning enthusiast who want to contribute to the society in best possible ways, painting the globe white

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.