Android Bluetooth to Arduino

Hello everybody !

I'm quite new to the world of Arduino, but since the beginning I wanted to use my phone (an Android) to control my Arduino through Bluetooth. (I'm also a beginner to Android by the way).

I did tones of research online in order to find something relevant and simple in order to do that. But I miserably failed.
But since patience is a virtue, I managed to gather information from almost everywhere and found this.

Without any pretension, here is a short how-to tutorial.
Maybe this post will help, maybe not, but at least I tried ^_^.

You need a Bluetooth Adapter plugged to your Arduino obviously.
For the Arduino code, I simply used the blink code and mixed it with Serial.read() function.
http://arduino.cc/en/Serial/read

I'm not gonna explain how android works but here's the link to download the IDE.

Before anything, I want to add something, I'm not a pro in programming, like not at all, and I'm not a native English speaker, so I apologize for the mistakes I will make and for the non-scholarly terms I will use. (Remember that while reading, please).

Since I just want to use my App with my arduino, I hardcoded its Mac Address in the code.

First thing first you're gonna need to test if the bluetooth in your phone is enabled or not and if you can use it.

	private void CheckBt() {
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		if (!mBluetoothAdapter.isEnabled()) {
			Toast.makeText(getApplicationContext(), "Bluetooth Disabled !",
					Toast.LENGTH_SHORT).show();
                   /* It tests if the bluetooth is enabled or not, if not the app will show a message. */
		}

		if (mBluetoothAdapter == null) {
			Toast.makeText(getApplicationContext(),
					"Bluetooth null !", Toast.LENGTH_SHORT)
					.show();
		}
	}

You can invoke that method in the onCreate method or whenever you want to (before trying to make a connection obviously).

The connect part is quite simple, in that case the method was triggered by clicking on a button :

	public void Connect() {
		BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
		Log.d("", "Connecting to ... " + device);
		mBluetoothAdapter.cancelDiscovery();
		try {
                        btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
/* Here is the part the connection is made, by asking the device to create a RfcommSocket (Unsecure socket I guess), It map a port for us or something like that */
			btSocket.connect();
			Log.d("", "Connection made.");
		} catch (IOException e) {
			try {
				btSocket.close();
			} catch (IOException e2) {
				Log.d("", "Unable to end the connection");
			}
			Log.d("", "Socket creation failed");
		}
		
		beginListenForData();
               /* this is a method used to read what the Arduino says for example when you write Serial.print("Hello world.") in your Arduino code */
	}

Then the method to actually Send stuff to the arduino.

	private void writeData(String data) {
		try {
			outStream = btSocket.getOutputStream();
		} catch (IOException e) {
			Log.d(TAG, "Bug BEFORE Sending stuff", e);
		}

		String message = data;
/* In my example, I put a button that invoke this method and send a string to it */
		byte[] msgBuffer = message.getBytes();

		try {
			outStream.write(msgBuffer);
		} catch (IOException e) {
			Log.d(TAG, "Bug while sending stuff", e);
		}
	}

Finally the part where the Android application actually read data just like I said earlier.

public void beginListenForData()   {
		 try {
				inStream = btSocket.getInputStream();
			} catch (IOException e) {
			}
		 
	        Thread workerThread = new Thread(new Runnable()
	        {
	            public void run()
	            {                
	               while(!Thread.currentThread().isInterrupted() && !stopWorker)
	               {
	                    try 
	                    {
	                        int bytesAvailable = inStream.available();                        
	                        if(bytesAvailable > 0)
	                        {
	                            byte[] packetBytes = new byte[bytesAvailable];
	                            inStream.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()
	                                        {
	                                        	
	                                        	if(Result.getText().toString().equals("..")) {
	                                        		Result.setText(data);
	                                        	} else {
	                                        		Result.append("\n"+data);
	                                        	}
	                                        	
	                                        	/* You also can use Result.setText(data); it won't display multilines
	                                        	*/
	                                        	
	                                        }
	                                    });
	                                }
	                                else
	                                {
	                                    readBuffer[readBufferPosition++] = b;
	                                }
	                            }
	                        }
	                    } 
	                    catch (IOException ex) 
	                    {
	                        stopWorker = true;
	                    }
	               }
	            }
	        });

	        workerThread.start();
	    }

I took it online so I can't really tell you much about that other that it works.
From what I can understand this method creates a Thread that checks whether there's something or not in the buffer and display it in the Result TextView.

Don't forget to add those two lines in your manifest.

Otherwise the app will crash.

Here's the full code :

There you go.

Hope it wasn't too useless and boring and maybe somewhat interesting, it helped me to understand Bluetooth SPP.

Maybe it will be simpler to upload the project so, here it is.

Project Android - ArduinoBluetooth.zip (1.21 MB)

Thanks for sharing!

Will try out. Thanks.

ok this may sound dumb... I have the android SDK. where do I put this code?

It might be a bit late, but the code goes in your Main Activity at least that's where I put it.
If you want to learn more about Android Development, here's a pretty nice video tutorial :

The website covers lots of programming languages.
(I don't own this website, nor i'm related to it, I just find it very good and pretty complete at least to start)

In addition, for those who might be interested, I used a Bt Adapter called JY-MCU, it's the cheapest one I could find on the bay.
It works fine, it's a slave device though, so you can't scan nor initiate a connection with it.

Do you know if this bluetooth module will work with iOS? For that matter, are there any bluetooth modules out there that work with both Android and iOS?

Hey Jon17,

If you have the project with this code and its other parts available could you post a link to download it? I'm having some problems getting mine to not crash when it opens.

I second the1cyrus's request. Please do post the entire project, I too am having troubles fixing some errors.

I'm pretty new to this and I don't know if this is a dumb question but what is the code supposed to be in the activity_main.xml of this project?

Hello everyone !

I'm sorry I didn't answer earlier, lots of things to do.

I have my project uploaded in my Google Drive, here is the link :

I'm not realy sure it's the good project, you'll have to tell me since I'm not on the right computer to test it.
Hope it'll suit you.

Have a good evening !

hi! the android app. will still work if i will use this ? http://appinventor.mit.edu/ thanks

you could try this.https://play.google.com/store/apps/details?id=com.lovejoysa.btswitch

Thanks for sharing!

I have only used AppInventor so far fr basic Android apps. It is simple to design a basic interface with a few buttons. Of course, you need to use proper development tools for larger projects. There is a free online course coming up on Coursera: for Android development that may be interesting:

I started messing around with Bluetooth recently as well and created a small robot that I can control from my phone. I am documenting my progress here:

I'm very interested in this. I have several projects for the Arduino for which I need color screens, and having touchscreen controls would be a plus. Cheap Android tablets can be had for as low as $50, versus $80 or more for a 7 inch touchscreen.

At the moment, I have nothing more useful to add. I'm a rank newbie to Arduino programming, most of my programming experience was in solder and to a lesser extent in Basic.

polymorph:
I'm a rank newbie to Arduino programming, most of my programming experience was in solder and to a lesser extent in Basic.

Hi,
You don't need to learn Android programming to control your Arduino. Check out pfodDesigner
http://www.forward.com.au/pfod/pfodDesigner/index.html

pfodDesigner lets you build custom Android Menus and then generates the Arduino sketch that servers them up, via pfodApp, and handles the users button presses. You only need to add the action code to the sketch.

Here is an example menu designed by pfodDesigner. You can format the colour, text, number of buttons, font size and font style.
No Android programming required.

Jon17:
Don't forget to add those two lines in your manifest.

Otherwise the app will crash.

Please could you explain what does it means? Where is located this manifest file ?

Hello,

I tried your codes but I can't seem to turn ON/OFF the led using your writeData(). I think arduino does not receive the value from android. Please can you help me figure it out. By the way. Here's my sketch:

int led = 13;
char inbyte = '0';
void setup() {
Serial.begin(9600);
pinMode(led, OUTPUT);
digitalWrite(led, LOW);
}

void loop() {

if (Serial.available() > 0)
{
inbyte = Serial.read();
if (inbyte == '0')
{
//LED off
digitalWrite(led, LOW);
}
if (inbyte == '1')
{
//LED on
digitalWrite(led, HIGH);
}
}
}

Hi,,

I've been watching developments for two years toward implementation of a smartphone dialer. Now via Bluetooth and the Anaren AIR interface shown last month in Nuts & Volts, I'm interested in finding someone who can assemble a Java application for the LG840G, and other LG smartphones.

Initially, I may try to develop a VB application to mimic/demonstrate LG840G functionality via the Bluetooth interface to Arduino. This would simplify development of the demonstration of various ideas. Java development could happen in phase two, possibly using an emulator.

I'd like to develop the Arduino to VB connection using simple VB code. I'll bet VB will simply treat the Bluetooth connection as a COMM port, so a primitive VB to Arduino application that implements the connection via USB, will also support the Bluetooth connection. I'm guessing, all I need do is identify the Bluetooth COMM port and process buffer I/O sames as for USB which worked fine.

Once this is verified, I can develop VB functionality of the Java application I want to develop for the LG840G which I have prepaid for just $6/month until 2017. I could easily afford to get a second phone dedicated to development and testing at this price, but if a suitable emulator exists, I'll use it.

LG Java development SDK and requirements seem a little daunting, however there is open source available which can be hacked, adding Bluetooth support, and needed features...

Is anyone interested in this project?

LINK to LG840G SDK...

:slight_smile:

hello Jon17...

i am working on an android arduino project where i want to send data to arduino and in return i want the arduino to send the data back to android..i am planning to send the data via a button in android such that if i press a button the android should instruct the arduino to display the data..the data is the temperature sensor which is connected to the arduino mega 2560 board..

i downloaded your app from the forum and i ran it in eclipse by connecting it to my android mobile but when the app runs it shows a message "Unfortunately Light Remote has stopped working"...even before turning on the bluetooth ...

i dnt know what is wrong with it...

i need your help i am using the latest version of eclipse with a target sdk of 21...please i need your help in figuring out what is wrong ..

I copied and pasted this; ArduinoBluetoothAndroid - Pastebin.com into sketch and then clicked upload. It said there is an error: stray '@' in program.

All I want to do is enable my Arduino Duemilanove to except bluetooth to control a servo motor using the Android App on Google Play.

I have no knowledge of all this Arduino stuff so I am hoping that someone here can guide a dummy step by step.

I promise I will go away then.