Login

Bluetooth controlled Home Automation

Objectives

  • Create UI for bletooth app
  • Query the Bluetooth adapter for any paired devices
  • Scan nearby devices if target device is currently not paired
  • Navigate to a new Activity to control our device via Bluetooth

Let’s Begin!

In this module we will learn how to create an app to control your household appliances from your smartphone over bluetooth. We will learn how to use the bluetoothAdapter that provides access to Bluetooth features of our android smartphone.

Creating the UI

Create two listViews one for paired devices and the other for newDevices. Aslo create a scan button which will scan the surroundings for any bluetooth devices.

This is what your activity_main.xml will look like.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

 

List view

 

Also each item of the listView should be a textView so we define this textView in a separate layout file called device_name.xml

This is how device_name.xml will look like

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.
Next come back to mainActivity and initialize required variables.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

The above if-else if check terminates the app if Bluetooth is not supported.

If Bluetooth is supported but not currently enabled it sets up an intent requesting the user to activate Bluetooth, and expects to get the enableBtIntent integer as the result of this action.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

We check the result of enableBtIntent intent by overriding onActivityResult outside onCreate if the return value the integer RESULT_CANCELLED we show a toast asking the user to provide permission else the user has already granted permission and we are good to go.

Setup the onClick method for scanButton that calls doDiscovery method explained later in Discover devices section and setup ArrayAdapters for pairedDevices list and newDevices list inside oncreate

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

Both the arrayadapters are taking device_name.xml as the layout for each item of the listView. 

Also register a broadcast receiver to receive any newly found device and to know when the discovery process has terminated.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

Querying for paired devices

Get a list of currently paired devices and display them on the listView, if none are found display message saying no paired devices found.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

Override onDestroy method which gets called hen the activity is terminated, to cancelDiscovery and unregister the broadcastReceiver.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

Discover devices

Set the progressbar to visible and check if the bluetoothAdapter is already discovering, if it is then cancel and restart the discovery.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

Setup the broadcast receiver to send any discovered device back to the registered receiver, also when the discovery is finished set the progressbar’s visibility to false and ask the user to connect to a device. If no devices are available then display that inside the listView.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

Setup an onItemClickListener to define the behaviour for listItem clicks

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

When we click any device from either pairedDevices list or newDevices list, first cancel discovering new devices as we are about to connect. Get the clicked devices MAC adrres and put it inside an intent and make the intent goto LedControl class.

This is how mainActivity should finally look like

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

Now create a new empty activity called LedControl. Setup its UI to contain a simple textview and three buttons for ON,OFF and DISCONNECT. This is how the activity_led_control should look like

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

 

activity_led_control layout

 

Now comeback to LedControl class

Initialize all required variables

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

Inside onCreate get a reference to all the buttons and receive the intent that started this activity and extract the devices bluetooth device’s MAC address that came with the intent and setup onClick listeners for all the three buttons.


To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

Then call the asyncTask that establishes a Bluetooth connection to the target device inside onCreate.new ConnectBT().execute(); Then outside onCreate setup helper methods for turnOnLed ,turnOffled and Disconnect


To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

The turn on and turnoff methods essentially are sending messages to the target device in the form of bytestream to turn the ledOn AND Off via the established socket connection. Now define the AsyncTask that establishes the connection


In the preExecute method make the progressDialog visible, inside doInBackground if the socket is null or currently not connected then create an RFComm channel and call connect on the newly created socket.Inside catch block set connectSuccess to false and handle any exceptions that might get thrown at us  In onPostExecute check the status of connectSuccess if it is false create a toast informing the user that Bluetooth is not connected else set isBtConnected boolean to true and dismiss the progressDialog.

This is how LedControl should finally look like.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.

Testing the app

To test the app in realTime we cann connect an led to a nodemcu board to mimic an appliance and then try controlling that led via our Bluetooth app.Connect a Bluetooth module to nodeMCU and connect its Tx pin to nodeMCU pin D7 and its Rx pin to nodeMCU pin D8.

Connect the led to pin D5 and install the softWareSerial library from manage libraries window of Arduino.The nodeMCU code seems pretty selfexplanatory.The traditional Tx,Rx pins of nodeMCU are utilized for transmitting and receiving serial data via USB to computer so we are defining one more pair of Rx,Tx i.e (D7,D8) to send and receive serial data that is coming from our Bluetooth app.

To copy the code, right click on view raw at the bottom of the code, click on open link in new tab and then copy the code.
Now if everything is setup correctly whenever you connect to the Bluetooth module from the Bluetooth app and click on ON btton f LedControl you should see the led switching on, and similarly you can turn the led OFF using the OFF button and disconnect from the Bluetooth device using the disconnect button.

 

We would love to see what you build out of these learnings!

Click here to submit your projects, share it with the world and stand a chance to be rewarded.

top

Knowledge and Content by Li2 Technologies | © 2021 NASSCOM Foundation | All rights reserved

X