Home Automation Using arduino ,HC-05 Bluetooth Module and Android application.-Part2

Daya Nithi
4 min readSep 23, 2020

--

In this tutorial we will try to highlight the embedded android application used to communicate.

First goes the designing part. We assume you have basic knowledge about deigning in android and omits the design code.

Android Iot

So here First we check the available Bluetooth. Then we will pair it with HC-05 and In Second screen we will select the Room to automate. Then we will Try to ON/Off the desired IOT such as light /Fan etc.

Paired devices screen code.

public class DeviceList extends AppCompatActivity
{
//widgets
Button btnPaired;
ListView devicelist;
//Bluetooth
private BluetoothAdapter myBluetooth = null;
private Set<BluetoothDevice> pairedDevices;
public static String EXTRA_ADDRESS = "device_address";

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);

//Calling widgets
btnPaired = (Button)findViewById(R.id.button);
devicelist = (ListView)findViewById(R.id.listView);

//if the device has bluetooth
myBluetooth = BluetoothAdapter.getDefaultAdapter();

if(myBluetooth == null)
{
//Show a mensag. that the device has no bluetooth adapter
Toast.makeText(getApplicationContext(), "Bluetooth Device Not Available", Toast.LENGTH_LONG).show();

//finish apk
finish();
}
else if(!myBluetooth.isEnabled())
{
//Ask to the user turn the bluetooth on
Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon,1);
}

btnPaired.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
pairedDevicesList();
}
});

}

private void pairedDevicesList()
{
pairedDevices = myBluetooth.getBondedDevices();
ArrayList list = new ArrayList();

if (pairedDevices.size()>0)
{
for(BluetoothDevice bt : pairedDevices)
{
list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address
}
}
else
{
Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
}

final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
devicelist.setAdapter(adapter);
devicelist.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked

}

private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
{
public void onItemClick (AdapterView<?> av, View v, int arg2, long arg3)
{
// Get the device MAC address, the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);

// Make an intent to start next activity.
Intent i = new Intent(DeviceList.this, MainActivity1.class);

//Change the activity.
i.putExtra(EXTRA_ADDRESS, address); //this will be received at ledControl (class) Activity
startActivity(i);
}
};

Here we will list the devices in listview using adapater on clicking the particular device it will move to next screen.

In the Next screen we will pass the device address/IpAddress

Ipaddress=    intent.getStringExtra("device_address")

So in the next screen we will receive the same ipaddress to make connection

address = intent.getStringExtra("device_address") //recei

So the important part comes here we will connect to the device using an async task. Even though its deprecated . For study purpose.

inner   class ConnectBT : AsyncTask<Void?, Void?, Void?>() // UI thread
{
private var ConnectSuccess = true //if it's here, it's almost connected
override fun onPreExecute() {
// progress = ProgressDialog.show(applicationContext, "Connecting...", "Please wait!!!") //show a progress dialog
}

override fun doInBackground(vararg devices: Void?): Void? //while the progress dialog is shown, the connection is done in background
{
try {
if (btSocket == null || !isBtConnected) {
myBluetooth = BluetoothAdapter.getDefaultAdapter() //get the mobile bluetooth device
val dispositivo: BluetoothDevice = myBluetooth!!.getRemoteDevice(address) //connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID) //create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery()
btSocket?.connect() //start connection
}
} catch (e: IOException) {
ConnectSuccess = false //if the try failed, you can check the exception here
}
return null
}

override fun onPostExecute(result: Void?) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result)
if (!ConnectSuccess) {
msg("Connection Failed. Is it a SPP Bluetooth? Try again.")
finish()
} else {
msg("Connected.")
isBtConnected = true
}
progress?.dismiss()
}




}

How to write to Bluetooth Serial connection.

This part writes data to serial connection HIGH input. It will make the Arduino pin HIGH

if (btSocket != null) {
try {
btSocket!!.outputStream.write("1".toByteArray())
} catch (e: IOException) {
msg("Error")
}
}

This part writes data to serial connection Low input. It will make the ardunio pin Low.

if (btSocket != null) {
try {
btSocket!!.outputStream.write("2".toByteArray())
} catch (e: IOException) {
msg("Error")
}
}

We can make different logic based on our needs.

So This is the simple code and design to communicate to Bluetooth module HC-05 . This BT Module communicates with Arduino using serial comm.

Voila we have completed the android app too.

Follow up for more tutorials.

--

--

Daya Nithi

6+ years of development of android applications. Exploring Flutter and more to come.