In this article I will show how to control an electrical appliance remotely from your Android device using bluetooth.
The hardwares used in this project are:
1. Android Mobile
2. Bluetooth Module
3. Arduino UNO R3
4. 5V Relay Module
Softwares used:
1. Eclipse IDE configured for android development
2. Arduino compiler
Bluetooth Module Details:
JY-MCU Arduino Bluetooth Wireless Serial Port Module
Default password: 1234
Baud rate: 38400
Dimensions: 1.73 in x 0.63 in x 0.28 in (4.4 cm x 1.6 cm x 0.7 cm)
PINOUT
PIN DESCRIPTION
1 KEY
2 VCC
3 GND
4 TXD
5 RXD
Adruino Code:
Bluetooth switch arduino
***********************/
int state = 0;
int incomingByte;
void setup() {
//set pin 12 to output mode
pinMode(12, OUTPUT);
Serial.begin(9600);
}
void loop() {
// see if there's incoming serial data:
if (Serial.available() > 0) {
// read the oldest byte in the serial buffer:
incomingByte = Serial.read();
// depending on the incoming byte do the needful action
if (incomingByte == '1') {
digitalWrite(12, HIGH);
delay(500);
Serial.println("ON");
state=1;
}
else if (incomingByte =='2') {
digitalWrite(12, LOW);
delay(500);
Serial.println("OFF");
state = 0;
}
}
if(state)
Serial.println("ON");
else
Serial.println("OFF");
delay(250);
}
Here is the android user interface, it just works anyway..
For Android part I changed the code from here a little bit:
This is how the code works basically:
1. On click of the Open button it calls findBT() and openBT() methods
2. findBT() method searches for all Paired bluetooth devices (in this case it tries to find a bluetooth device named ‘linvor’ and saves it, in your case this name can be different and hence need to replace in the code)
3. openBT() using UUID (universally unique identifier) creates a bluetooth socket connection on a bluetooth device by calling connect(). Then it opens input and output streams on this socket connection. And finally calls beginListenForData().
4. beginListenForData() opens a thread where it listens for data and if there is data it accumulates and shows them in a label.
5. At the same time there are ON and OFF button in the interface which sends data via output stream, thread is still running and listening for data.
6. Arduino received the data by his bluetooth companion and acts on that data using his logic also replies back to the android device.
7. In the Arduino site similar to Android there is Serial.read() which read the serial data and returns as int which is then matched for setting output pin to LOW or HIGH state. And there is Serial.println() for sending data back to Android for confirming the Status.
When pairing with the Bluetooth device (linvor) from Android it might ask a password which is generally ‘1234’.
Android Code:
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class BluetoothTest extends Activity
{
TextView myLabel;
EditText myTextbox;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button openButton = (Button)findViewById(R.id.open);
// Button sendButton = (Button)findViewById(R.id.send);
Button closeButton = (Button)findViewById(R.id.close);
Button onButton = (Button)findViewById(R.id.onButton);
Button offButton = (Button)findViewById(R.id.offButton);
myLabel = (TextView)findViewById(R.id.label);
// myTextbox = (EditText)findViewById(R.id.entry);
//Open Button
openButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
findBT();
openBT();
}
catch (IOException ex) { }
}
});
//Send Button
/*sendButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
sendData();
}
catch (IOException ex) { }
}
});*/
//ON SWITCH
onButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
onButton();
} catch (Exception e) {
// TODO: handle exception
}
}
});
//OFF SWITCH
offButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
offButton();
} catch (Exception e) {
// TODO: handle exception
}
}
});
//Close button
closeButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
closeBT();
}
catch (IOException ex) { }
}
});
}
void findBT()
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
myLabel.setText("No bluetooth adapter available");
}
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals("linvor")) //this name have to be replaced with your bluetooth device name
{
mmDevice = device;
Log.v("ArduinoBT", "findBT found device named " + mmDevice.getName());
Log.v("ArduinoBT", "device address is " + mmDevice.getAddress());
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
}
void openBT() throws IOException
{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("Bluetooth Opened");
}
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
myLabel.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
workerThread.start();
}
void sendData() throws IOException
{
String msg = myTextbox.getText().toString();
msg += "";
//mmOutputStream.write(msg.getBytes());
//mmOutputStream.write(msg.getBytes());
//mmOutputStream.flush();
//mmOutputStream.close();
//mmSocket.close();
myLabel.setText("Data Sent"+msg);
}
void onButton() throws IOException
{
mmOutputStream.write("1".getBytes());
}
void offButton() throws IOException
{
mmOutputStream.write("2".getBytes());
}
void closeBT() throws IOException
{
stopWorker = true;
mmOutputStream.close();
mmInputStream.close();
mmSocket.close();
myLabel.setText("Bluetooth Closed");
}
}
As you can see this is just scratch, by adding more relays you can control more than one devices upto as much as your arduino board supports. Also fine tuning the code there are lot more possibilities. Let me know about your project in comments and/or any suggestions most welcome.
49 Responses to “Android wireless remote switch : control home appliances (Android + Bluetooth + Arduino)”
Felipe César
Hello, i’m just begning to wor wuth android apps. So i’m using Eclipse, how do i start with your project in my IDE? Create a new android Application and copy paste your code to one page? Can you help me?
Thanks!
zamanisgeek
Hey you can download my source from here: https://dl.dropboxusercontent.com/u/15276675/Remote.rar. It is a dropbox link. However for security reason you also need to use Safe Monk do download the code from dropbox. It is also an Eclipse project. just import to your eclipse and have fun!
Felipe César
Thanks a lot Zamanisgeek!
Sorry for the bad english….
asa
not reading this app help me
zamanisgeek
have a look at here: http://mattgemmell.com/2008/12/08/what-have-you-tried/
kimi
hi..
do you have any idea if I want to use PIC16F877A to replace the Arduino
tq
zamanisgeek
sorry but it will be less costly if you can do it
Tejas Kuvalker
hey please help me. we are doing a similar project with anduino leonardo will it work if i replace the arduino uno with it……..also please send me an ckt diagram of the project
zamanisgeek
leonardo should work. please follow the tutorial circuit diagram should be obvious, however if you don’t get a specific point let me know.
Tejas Kuvalker
can you plz tell me how the relay module is connected..
zamanisgeek
sry for the late reply. it is just a digital output from arduino and two power supply +5v, 0.
Tejas Kuvalker
i had done a app in java using netbeans now after seeing your android code thinking of doing and andriod app can you please help me with Eclipse IDE because when i try to import your code it’s gives me a lot of err….
plz can u tell what extra plug-in eclipse needs or can u post a link of eclipse that will help me.
Jared Andrews
I am new to using android and some terms are foreign to me
zamanisgeek
it just takes some time. after a while it becomes familiar. happy programming 🙂
Jason
If I copy the code into Eclipse it gives me an error on this line
“for (BluetoothDevice device : pairedDevices) {”
–> Type mismatch: cannot convert from element type Object to BluetoothDevice
Any ideas?
Lloyd
Jason,
I had the same error and resolved it by finally cnanging the line starting “Set pairedDevices..”
to:
Set pairedDevices…. (inserting )
this cleared the error.
Lloyd
Something strange here with wordpress. It does not allow use of the “greater than” and “less than” symbols or anything contained within them.. I replied that after “Set” there must be “less than” BluetoothDevice “greater than” to remove the error.
When Zaman entered his code into wordpress the greater than and less than signs and the BluetoothDevice contained within were eliminated by wordpress, leading to the error. Zaman’s original code is not downloadable from dropbox so cutting and pasting the android source from above replicates the error of omission of that inserted “BluetoothDevice”.
zamanisgeek
sorry for the outdated link. new source link is provided in the comment. thanks for looking
bonz
Hi good Day,
May i ask the step by step procedure on how construct that project because I got little bit confuse on how to create that..
please help me…. I want to made it perfectly and successfully…
Nathalie Joy Galia
Hai,.!! I would like to ask if what is the use of 5V relay module and could we use arduino for bigger voltage for lights?
zamanisgeek
Hi, About relay: http://lmgtfy.com/?q=5V+relay and sure you can!
Lucas
Hey Zamanis.. i get the error “Unable to resolve target ‘android-8′”, when i run ur code. What should i do?
zamanisgeek
Please see in the android code you need to manually set your blue-tooth device’s name to which it is trying to connect. Your error might be because of device name mismatch
Vishal Nalawade
Hi, i want all the information about “BLUE KEY WIRELESS TECHNOLOGY” How it works, what are the technical specifications etc.
Nathalie Joy Galia
hai.. It’s me again,I am now studying your codes.. 🙂 could I download it?… 🙂
Sundeep
I am very much interested in your design. Was offering something pretty similar thing on freelancer site (actually it is a project that has gone wrong w.r.t. bluetooth switch using android application). If interested, please add me on sundeep_ballare on skype. Your help would be greatly appreciated.
Priority would be an absolute delight.
Lloyd
Zamanis, very nice work with simplifying the discovery and opening of a known bluetooth device.
I am having some difficulty getting my Arduino to see anything other than OFF, however, the open and close buttons work fine but on and off do nothing and all I get are continuous OFF reading in my Arduino com window with not turning on and off of my digital output. I guess I will try to see if Arduino needs an ASCII equivalent or something. Anyone else have this problem?
Nathalie Joy Galia
Zaman,..I cant run this code..it has a problem…
Avinash
hi Zaman ,
can you post or mail the detailed circuit connections for interfacing arduino UNO board with relay switch and bluetooth ?
thanks in advance
Avinash
hi
I Would like to try this , if any one have detailed circuit connections for interfacing arduino UNO board with relay switch and bluetooth pl let me know?
thanks in advance
anonymous
little bit of googling should find it 🙂
Shelas Doox
hie
I would like to design a room temperature control circuit which would be having a temperature sensor reading the values of the temperature and compare them with the setpoints that the user would have fed to the system and these will results in the switching on and off of a fan and/or a heater…Is this possible using the arduino micocontroller?
anonymous
hi I think yes as long as arduino supports PID loop control 🙂
Mark
App crashes after I push the OPEN button on my phone. How can I fix it?
Dexter
Hey Zaman
when i run you android programm and click the button “open” and “close”,
the app crash so that i cannot open the BT and cannot connect to the device
are there anyone has this similar situation?
anonymous
this might be due to various reason, what logcat says?
Dexter
how to read the logcat?
actually i run it in a emulator or in a new android phone
when i press the open or close, it crashes 🙁
so painful
1111coiso
Any solution for this problem?
author
try changing bluetooth device name in the code..
Soham
https://www.dropbox.com/s/rymuqc9g1a4mne9/Remote.rar.
this link is not working . please send me source code on soham.dalwadi@yahoo.com
anonymous
sorry again, here is the new link: https://dl.dropboxusercontent.com/u/15276675/Remote.rar
Dexter
Sometimes i import your codes, the eclipse said it has error
but sometime no error
when i export it as apk file,and install it,
it crashes again when i press the open button and close button.
Why?
ankit
sir I want to know that which app is available for free in google market for controlling 4 relays and please send me the codes for 4 relay controlling…. pleaseeeeee…..!!!!!!!
ankit
m using arduino uno
ankit
m using arduino uno. bluetooth module hc-05 n 4 releys
sarauai
it gets an error at line for(BluetoothDevice device : pairedDevices) on pairedDevices, can u please say y it gets an error
shilafarhah
why you use android instead of apple? what’s the different. and why dobt you use raspberry pi instead of arduino?
random
App force closes when you click open. Any help? Log cat displays:
04-23 18:45:00.458: E/AndroidRuntime(25235): FATAL EXCEPTION: main
04-23 18:45:00.458: E/AndroidRuntime(25235): Process: Android.Arduino.Bluetooth, PID: 25235
04-23 18:45:00.458: E/AndroidRuntime(25235): java.lang.NullPointerException
04-23 18:45:00.458: E/AndroidRuntime(25235): at Android.Arduino.Bluetooth.BluetoothTest.openBT(BluetoothTest.java:152)
04-23 18:45:00.458: E/AndroidRuntime(25235): at Android.Arduino.Bluetooth.BluetoothTest$1.onClick(BluetoothTest.java:59)
04-23 18:45:00.458: E/AndroidRuntime(25235): at android.view.View.performClick(View.java:4480)
04-23 18:45:00.458: E/AndroidRuntime(25235): at android.view.View$PerformClick.run(View.java:18673)
04-23 18:45:00.458: E/AndroidRuntime(25235): at android.os.Handler.handleCallback(Handler.java:733)
04-23 18:45:00.458: E/AndroidRuntime(25235): at android.os.Handler.dispatchMessage(Handler.java:95)
04-23 18:45:00.458: E/AndroidRuntime(25235): at android.os.Looper.loop(Looper.java:157)
04-23 18:45:00.458: E/AndroidRuntime(25235): at android.app.ActivityThread.main(ActivityThread.java:5872)
04-23 18:45:00.458: E/AndroidRuntime(25235): at java.lang.reflect.Method.invokeNative(Native Method)
04-23 18:45:00.458: E/AndroidRuntime(25235): at java.lang.reflect.Method.invoke(Method.java:515)
04-23 18:45:00.458: E/AndroidRuntime(25235): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1069)
04-23 18:45:00.458: E/AndroidRuntime(25235): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:885)
04-23 18:45:00.458: E/AndroidRuntime(25235): at dalvik.system.NativeStart.main(Native Method)
Kevin
Hi, i want to let android receive the data sent from arduino. However, i can’t read the data sent from arduino. Do you have any solution? Thanks for your article.