Arduino Projects

Android Toggle Button for Automation using Arduino & Bluetooth

Android Toggle Button, Description:

Android Toggle Button

Android Toggle Button for Automation using Arduino & Bluetooth– A few months back I uploaded an article on how to create your own android cell phone application to control an LED using Arduino, HC-05 Bluetooth module and an Android cell Phone. For the best understanding, I used only two buttons light ON and light OFF. The two buttons were used to turn ON and turn OFF the led. You can read this article.


Android Toggle Button

Using two buttons to control an LED or any other load AC or DC type is good for beginners. But when it comes to the final app development where you need to control multiple loads, this seems very impractical to have two buttons for every load. If you want to control 8 electrical loads you will need 16 buttons. After covering the basics, I decided to make another tutorial focusing on the Android toggle button or switch.

Instead of using two buttons, the same thing can be done by using only one button which is called a toggle switch or a toggle button. Previously I used an LED, so that’s why this time I decided to use a 220Vac light bulb. Later you can increase the number of toggle buttons to control multiple loads. You can download some cool png images of the electrical appliances and use them as the buttons, which you will learn in a minute.

For the practical demonstration, circuit diagram explanation, and programming watch the video given at the end of this article.

Without any further delay let’s get started!!!

Amazon Links:

12v Adaptor:

Arduino Uno

Arduino Nano

Mega 2560:

Bluetooth Module: Hc-05:

1n4007 diode:

10k Resistor:

2n2222 NPN transistor

12V SPDT Relay:

One-Channel Relay Module:

2-channel relay module:

12v SPDT type 4-channel relay Module:

8 channel Relay Module

Other Tools and Components:

Top Arduino Sensors:

Super Starter kit for Beginners

Digital Oscilloscopes

Variable Supply

Digital Multimeter

Soldering iron kits

PCB small portable drill machines

*Please Note: These are affiliate links. I may make a commission if you buy the components through these links. I would appreciate your support in this way!

Android Toggle Button Circuit Diagram:

Android Toggle Button

The HC-05 or HC-06 Bluetooth Module Tx and Rx pins are connected with the Arduino’s pin number 2 and pin number 3. While the Vcc and GND pins of the Bluetooth module are connected with the Arduino’s 5 Volts and ground.

A 12 volts SPDT “Single Pole and Double Throw” type relay is used to control the AC load. This relay has a total of 5 pins, out of these 5 pins two are the coil pins, common, Normally Open, and normally closed. This relay is controlled by the driver circuit which consists of the Transistor and a 10k ohm resistor. This is a general-purpose NPN transistor. As you can see the emitter is connected with the Ground, the collector is connected with the relay coil pin while the other side of the relay coil is connected with the 12 volts. The base is connected with the Arduino’s pin number 13 through a 10k resistor. A diode is connected across the relay coil, which is used for the back EMF protection. You can use a readymade relay module or you can make the one by yourself.

About HC 05 Bluetooth Module:

The HC-05 Bluetooth Module used in this project is given below.

Android Toggle Button

Android Toggle Button

As you can see clearly in the images above, this Bluetooth module has a total of 6 male headers which are clearly labeled as STATE, RXD, TXD, GND, VCC, and EN. The EN pin has a push button that is used during the time when this module is needed to be entered into the AT commands Mode. I have a very detailed tutorial on how to use the AT commands to change the name of the Bluetooth module and the pairing code. You can watch the following video.

Relay Module with Arduino

Android Toggle Button

As you can see on the left side is the 3 channel relay module, but out of these three relays currently, I am using only one relay which is connected with the Arduino’s pin number 13 and make sure you connect the relay module ground ”blue wire” with the Arduino’s ground. The Bluetooth Module is connected with the Arduino as per the circuit diagram already explained.

Arduino Bluetooth Programming:

#include <SoftwareSerial.h>
SoftwareSerial Blue(2, 3);
long int data;

int relay1 = 13; // DEVICE 1
long int password1 = 92;// light on
long int password2 = 551;// to off

void setup()

pinMode(relay1, OUTPUT);
digitalWrite(relay1, LOW);




void loop()

while(Blue.available()==0) ;

data = Blue.parseInt();

if (data == password1)

Serial.println(“device1 on “);

if( data == password2)
Serial.println(“device1 off”);


Arduino Bluetooth Program explanation:

I started off by including the Software Serial library. The SoftwareSerial library is used to create Serial Ports. You can define multiple Serial Ports. If you are using the Arduino Mega then you don’t need to use the SoftwareSerial library as you know in Arduino Mega we have multiple Serial ports. But when it comes to the Arduino we have only one Serial Port which is available on pin number 0 and pin number 1. As I always say never use the Arduino’s default Serial Port for communication with other devices. The Arduino’s default Serial Port should only be used for debugging purposes. So using the SoftwareSerial library I defined a serial port of the Bluetooth module on pin number 2 and pin number 3 of the Arduino.

The variable data is of the type long integer and is used to store the number sent from the Bluetooth application. This number can be 6 digits long to increase security.

Relay is connected with the Arduino’s pin number 13 which is already explained in the circuit diagram.

long int password1 = 92;

long int password2 = 551;

These are the two passwords that are used to turn ON and turn OFF the load. You can increase the security by using numbers consisting of 6 digits.

In every Arduino or Mega program, we have at least two functions which are the void setup and void loop functions. The void setup function executes only one time when the Arduino or Mega board is turned ON, while the void loop function executes forever until we turn OFF the Board. In the void setup function, the relay is set as the output using the pinMode() function. The relay is turned OFF by using digitalWrite function and finally, the Serial communication is activated.

In the void loop function,

while(Blue.available()==0) ;

If the Arduino has not received any data from the Bluetooth module then simply wait over here.



  data = Blue.parseInt();


This condition means if the Arduino has received data from the Bluetooth then store the received number in data and compare this with the predefined values and then turn ON and turn OFF the relay accordingly. So that’s all about Arduino programming.

Android Toggle Button app development:

About Bluetooth:

The Android platform provides Bluetooth network stack support, which allows a phone to exchange data wirelessly with other Bluetooth devices. With the Android Bluetooth APIs, the application framework provides access to the Bluetooth features. These APIs allow wireless connection of applications to other Bluetooth devices, allowing point-to-point and wireless multipoint features.

Using the Bluetooth APIs, the following can be achieved by an Android application:

Check for other phones with Bluetooth

For paired Bluetooth devices, ask for a local Bluetooth adapter

Establish channels for RFCOMM

Link to other phones by finding the service

Data transfer from and to other phones

Manage multiple links

This page is dedicated to Classic Bluetooth. Classic Bluetooth is the right choice for more battery-intensive operations, including streaming and Android phone connectivity. For low-powered Bluetooth devices, Android 4.3 (API level 18) introduces Bluetooth Low Energy API support. See Bluetooth Low Energy for more information. The document defines different models for Bluetooth, including the Health System Profile. It then describes how to use the Android Bluetooth APIs to accomplish the four main tasks required for Bluetooth communication: setting up Bluetooth, identifying devices that are either paired or accessible in the local area, linking devices, and transferring data between devices.

The basics of Bluetooth

To allow Bluetooth devices to transmit data between themselves, they must first use a pairing method to form a communication channel. For incoming connection requests, one device, a discoverable device, makes itself available. Another device uses a service discovery process to find the discoverable device.

The two devices complete a bonding process where they exchange security keys after the discoverable device acknowledges the pairing request. These keys are cached for later use by the devices. The two devices exchange information after the pairing and bonding processes are complete. The device that initiated the pairing request will release the stream that connected it to the discoverable device when the session is complete. Nevertheless, the two devices remain connected, so they can automatically reconnect during a future session so long as they are within each other’s reach and the bond has not been broken by either system.

Bluetooth enabling permission

You must claim two permissions to use Bluetooth features in your software. BLUETOOTH is the first of these. To perform some Bluetooth communication, you need this permission, such as requesting a link, accepting a connection, and transferring data.

ACCESS FINE LOCATION is the other permission to be declared. Your device requires this permission because you can use a Bluetooth scan to collect information about the user’s location. This data can come from the user’s own phones, as well as from Bluetooth beacons used at places like shops and transit facilities.

You will declare the BLUETOOTH ADMIN permission in addition to the BLUETOOTH permission if you want your app to trigger network discovery or modify Bluetooth settings. Many applications only need this permission for local Bluetooth devices to be discovered. Unless the program is a “power manager” which modifies Bluetooth settings upon user request, the other features provided by this permission should not be used. Declare permission(s) for Bluetooth in your manifest application file. Don’t forget to add the Bluetooth permission in manifest.xml before you create the APK file.

xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:android=””

<uses-permission android:name=”android.permission.BLUETOOTH” />

<uses-permission android:name=”android.permission.BLUETOOTH_ADMIN” />

<activity android:name=”.Controlling”></activity>
<activity android:name=”.MainActivity”>
<action android:name=”android.intent.action.MAIN” />

<category android:name=”android.intent.category.LAUNCHER” />


Android Toggle Button app development:

First of all, open the Android Studio.

Android Toggle Button

Click on Start a new Android Studio project

Android Toggle Button

While Choose your project form is open.

Select the empty activity and click on the Next button

Android Toggle Button

After you click on the Next button, then configure your project form is opened, over here you set the project name, package name and you can select a directory where you want to store the application. Make sure the language is set to Java. So after you are done then you can click on the Finish button.

Android Toggle Button

Wait for app synchronization

Android Toggle Button

When your project is fully synchronized, as you can see the green dots in the following picture which is an indication that the synchronization is completed and we are ready for the next step.

Android Toggle Button

Before starting app design there are two main classes which is and

Now create a java class

Android Toggle Button

Enter name as the ActivityHelper and click ok

Android Toggle Button

And past below code code

package com.example.lightcontrol;

import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class ActivityHelper {
public static void initialize(Activity activity) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(activity);

String orientation = prefs.getString(“prefOrientation”, “Null”);
if (“Landscape”.equals(orientation)) {
} else if (“Portrait”.equals(orientation)) {
} else {

Android Toggle Button

Now create the second java class

Android Toggle Button

Enter class name as the preferrencesActivity and click ok

Android Toggle Button code
package com.example.lightcontrol;

import java.util.Map;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;

public class PreferencesActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener {
public void onCreate(Bundle savedInstanceState) {
// Using this for compatibility with Android 2.2 devices

public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference pref = findPreference(key);

if (pref instanceof ListPreference) {
ListPreference listPref = (ListPreference) pref;

if (pref instanceof EditTextPreference) {
EditTextPreference editPref = (EditTextPreference) pref;

protected void onPause() {


protected void onResume() {
Map<String, ?> keys = PreferenceManager.getDefaultSharedPreferences(this).getAll();

for (Map.Entry<String, ?> entry : keys.entrySet()) {
// Log.d(“map values”, entry.getKey() + “: ” + entry.getValue().toString());
Preference pref = findPreference(entry.getKey());
if (pref != null) {



Android Toggle Button

Now we will make a layout for the Search and connect buttons. The search button will be used for searching the Bluetooth module and the connect button will be used to connect with the paird Bluetooth module .

For this click on the small arrow symbol given with the bluetoothlight and find the Res and click on the small arrow to expand it, under the res then click on the layout to expand it and click on the activity_main.xml this will open the design screen.

Android Toggle Button

Now change the layout form constraint layout to linearlayout

Android Toggle Button

As you can see in the picture below.

Android Toggle Button

Now we make another linear layout within the main linearlayout

To create a button in XML we use the button attribute having some property that you can adjust as per your requirements.

Android Toggle Button

To check the design layout for this change from text mode to the design. As you can see at the end of the coding there are two button with captions Design and Text. You can click on the Design button. As you can see the mouse cursor.

Android Toggle Button

It’s a good programming practice to keep checking your design layout as you continue to program. So now we are done with two buttons with captions search and connect. Now we will add the code for the paired device, for this, we use the listview attribute. Click on the Design button to check.

Android Toggle Button

Now open the class

Android Toggle Button code

To remove  this error just click on the red bulb and select create id value resource

Android Toggle Button

And then click ok

Android Toggle Button

So now you can see the list_item.xml is created

Android Toggle Button

Open list_item.xml file and paste this code
LinearLayout xmlns:android=””
android:gravity=”center_vertical” >

<!– Defining where should text be placed. You set you text color here –>

android:textColor=”#000000″ />


Now we build the main controlling window, click on the package folder right now

Then New

Then Activity

And click on the Empty Activity

Android Toggle Button

Open  activity_controlling.xml

Android Toggle Button

Now change the layout form constraint layout to RelativeLayout

Android Toggle Button

Open the activity controlling.xml and switch the text type to the design mode

Android Toggle Button

Before creating toggle button first of all copy these two images in drawable folder which is giving below

Android Toggle Button

Android Toggle Button

Android Toggle Button

right click on drawable and click on the android resource file

Android Toggle Button

Resource file name is on_off and press ok and paste the below code
<?xml version=”1.0″ encoding=”utf-8″?>
<selector xmlns:android=””>
<item android:drawable=”@drawable/on” android:state_checked=”true”/>
<item android:drawable=”@drawable/off” android:state_checked=”false”/>


Android Toggle Button

Now open activity_controlling.xml and paste the below code
xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:android=””
android:text=”Programming Digest”



Finally, open the

Android Toggle Button

Android Toggle Button code

We are done with designing and coding. Now the next step is to create the APK file.

Creating Android Toggle Button application .apk file.

Click on the build menu then hover the mouse on build bundle/(apk) and click on the build apk

Android Toggle Button

And then wait for around one minute depending on your laptop or computer processing speed.

Android Toggle Button

After generating the Android Toggle Button application apk file then click on locate and transfer the app-debug.apk to phone and install

Android Toggle Button

Watch Video Tutorial:

Engr Fahad

My name is Shahzada Fahad and I am an Electrical Engineer. I have been doing Job in UAE as a site engineer in an Electrical Construction Company. Currently, I am running my own YouTube channel "Electronic Clinic", and managing this Website. My Hobbies are * Watching Movies * Music * Martial Arts * Photography * Travelling * Make Sketches and so on...

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button