Android and Arduino Bluetooth communication

In this post I will be talking about how to get an Arduino and an Android tablet talking to each other using Bluetooth

We will be using an Arduino Uno ($29.95) with a Silver Bluetooth Mate ($40.95) from SparkFun.com, and my Samsung Galaxy 7.0 running Android 2.3.4.

Wiring the bluetooth mate to the Arduino is really simple and spark fun has a great link on the product page explaining it. Here are the connections that need to be made:

Bluetooth Mate Arduino
CTS-I No connection (leave floating)
VCC 5V
GND GND
TX-O D2
RX-I D3
RTS-O No connection (leave floating)

To illustrate the connection between the Arduino the tablet we will be sending simple text messages back and forth between them. However, since the Arduino doesn’t really have a keyboard, we are going to plug the arduino into our pc and talk to it via a serial connection using usb.

The arduino code is fairly simple. In a nutshell is opens a serial connection to the computer, and a serial connection to the bluetooth mate. Any data received on one is written to the other and vice versa. Since we are going to be using the Arduino’s regular RX and TX lines for talking to the PC, we are going to have to use a software based serial connection on two other digital pins using the NewSoftSerial Arduino library which can be downloaded here. Just copy the folder in the zip to the libraries folder under your Arduno folder (for me it is at C:\Program Files\arduino-1.0\libraries)

Here is the Arduino code:

#include <SoftwareSerial.h>

int bluetoothTx = 2;
int bluetoothRx = 3;

SoftwareSerial bluetooth(bluetoothTx, bluetoothRx);

void setup()
{
  //Setup usb serial connection to computer
  Serial.begin(9600);

  //Setup Bluetooth serial connection to android
  bluetooth.begin(115200);
  bluetooth.print("$$$");
  delay(100);
  bluetooth.println("U,9600,N");
  bluetooth.begin(9600);
}

void loop()
{
  //Read from bluetooth and write to usb serial
  if(bluetooth.available())
  {
    char toSend = (char)bluetooth.read();
    Serial.print(toSend);
  }

  //Read from usb serial to bluetooth
  if(Serial.available())
  {
    char toSend = (char)Serial.read();
    bluetooth.print(toSend);
  }
}

That takes care of the Arduino side of things. The Android bits are little bit tougher.

The Android project we are going to write is going to have to do a few things:

  1. Open a bluetooth connection
  2. Send data
  3. Listen for incoming data
  4. Close the connection
But before we can do any of that we need to take care of a few pesky little details.  First, we need to pair the Arduino and Android devices. You can do this from the Android device in the standard way by opening your application drawer and going to Settings. From there open Wireless and network. Then Bluetooth settings. From here just scan for devices and pair it like normal. If it asks for a pin it’s probably 1234. You shouldn’t need to do anything special from the Arduino side other than to have it turned on. Next we need to tell Android that we will be working with bluetooth by adding this element to the <manifest> tag inside the AndroidManifest.xml file:
<uses-permission android:name=”android.permission.BLUETOOTH” />
Alright, now that we have that stuff out of the way we can get on with opening the bluetooth connection.  To get started we need a BluetoothAdapter reference from Android.  We can get that by calling
BluetoothAdapter.getDefaultAdapter();

The return value of this will be null if the device does not have bluetooth capabilities. With the adapter you can check to see if bluetooth is enabled on the device and request that it be turned on if its not with this code:

if(!mBluetoothAdapter.isEnabled())
{
   Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
   startActivityForResult(enableBluetooth, 0);
}

Now that we have the bluetooth adapter and know that its turned on we can get a reference to our Arduino’s bluetooth device with this code:

        Set pairedDevices = mBluetoothAdapter.getBondedDevices();
        if(pairedDevices.size() > 0)
        {
            for(BluetoothDevice device : pairedDevices)
            {
                if(device.getName().equals("MattsBlueTooth")) //Note, you will need to change this to match the name of your device
                {
                    mmDevice = device;
                    break;
                }
            }
        }

Armed with the bluetooth device reference we can now connect to it using this code:

        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
        mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
        mmSocket.connect();
        mmOutputStream = mmSocket.getOutputStream();
        mmInputStream = mmSocket.getInputStream();

This opens the connection and gets input and output streams for us to work with. You may have noticed that huge ugly UUID. Apparently there are standard UUID’s for various devices and Serial Port’s use that one. There are lists available out there, but I got this one from the Android documentation.

If everything has gone as expected, at this point you should be able to connect to your Arduino from your Android device. The connection takes a few seconds to establish so be patient. Once the connection is established the red blinking light on the bluetooth chip should stop and remain off.

Closing the connection is simply a matter of calling close() on the input and output streams as well as the socket

Now we are going to have a little fun and actually send the Arduino some data from the Android device. Make yourself a text box (also known as an EditText in weird Android speak) as well as a send button. Wire up the send button’s click event and add this code:

        String msg = myTextbox.getText().toString();
        msg += "\n";
        mmOutputStream.write(msg.getBytes());

With this we have one way communication established! Make sure the Arduino is plugged in to the computer via the USB cable and open the Serial Monitor from within the Arduino IDE. Open the application on your Android device and open the connection. Now whatever your type in the textbox will be sent to the Arduino over air and magically show up in the serial monitor window.

Sending data is trivial. Sadly, listening for data is not. Since data could be written to the input stream at any time we need a separate thread to watch it so that we don’t block the main ui thread and cause Android to think that we have crashed. Also the data written on the input stream is relatively arbitrary so there isn’t a simple way to just be notified of when a line of text shows up. Instead lots of short little packets of data will show up individually one at a time until the entire message is received.  Because of this we are going to need to buffer the data in an array until enough of the data shows up that we can tell what to do. The code for doing this and the threading is a little be long winded but it is nothing too complicated.

First we will tackle the problem of getting a worker thread going. Here is the basic code for that:

        final Handler handler = new Handler();
        workerThread = new Thread(new Runnable()
        {
            public void run()
            {
               while(!Thread.currentThread().isInterrupted() && !stopWorker)
               {
                    //Do work
               }
            }
        });
        workerThread.start();

The first line there declares a Handler which we can use to update the UI, but more on that later. This code will start a new thread. As long as the run() method is running the thread will stay alive. Once the run() method completes and returns the thread will die. In our case, it is stuck in a while loop that will keep it alive until our boolean stopWorker flag is set to true, or the thread is interrupted. Next lets talk about actually reading data.

The input stream provides an .available() method which returns us how many (if any) bytes of data are waiting to be read. Given that number we can make a temporary byte array and read the bytes into it like so:

                        int bytesAvailable = mmInputStream.available();
                        if(bytesAvailable > 0)
                        {
                            byte[] packetBytes = new byte[bytesAvailable];
                            mmInputStream.read(packetBytes);
                        }

This gives us some bytes to work with, but unfortunately this is rather unlikely to be all of the bytes we need (or who know its might be all of them plus some more from the next command).  So now we have do that pesky buffering thing I was telling you about earlier. The read buffer is just byte array that we can store incoming bytes in until we have them all. Since the size of message is going to vary we need to allocate enough space in the buffer to account for the longest  message we might receive. For our purposes we are allocating 1024 spaces, but the number will need to be tailored to your specific needs. Alright, back to the code.  Once we have packet bytes we need to add them to the read buffer one at a time until we run in to the end of line delimiter character, in our case we are using a newline character (Ascii code 10)

                            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;

                                    //The variable data now contains our full command
                                }
                                else
                                {
                                    readBuffer[readBufferPosition++] = b;
                                }
                            }

At this point we now have the full command stored in the string variable data and we can act on it however we want. For this simple example we just want to take the string display it in on a on screen label. Sticking the string into the label would be pretty simple except that this code is operating under a worker thread and only the main UI thread can access the UI elements. This is where that Handler variable is going to come in. The handler will allow us to schedule a bit of code to be executed by main UI thread. Think of the handler as delivery boy who will take the code you wanted executed and deliver it to main UI thread so that it can execute the code for you. Here is how you can do that:

                                    handler.post(new Runnable()
                                    {
                                        public void run()
                                        {
                                            myLabel.setText(data);
                                        }
                                    });

And that is it! We now have two way communication between the Arduino and an Android device! Plugin the Arduino and open the serial monitor. Run your Android application and open the bluetooth connection. Now what type in the textbox on the Android device will show up in the serial monitor window for the Arduino, and what you type in the serial monitor window will show up on the Android device.

The source code for both the Arduino and Android  is available at: http://project-greengiant.googlecode.com/svn/trunk/Blog/Android Arduino Bluetooth

Tagged , ,

107 thoughts on “Android and Arduino Bluetooth communication

  1. David says:

    Hi Matt,
    I’ve been trying to use your code, everything seems to work fine, however I can’t get any text to be sent or received in either direction.
    However the open and close buttons work because I can see the green light turn on, on the bluetooth modem whenever I open the connection, and goes back to flashing red when I close the connection.
    I’m using your exact code and here is my setup:

    Arduino Mega (ATmega1280)
    Bluetooth Mate Gold
    htc Android phone (Android v2.2)

    I’ve also added a function to flash an LED on send/receive. When I type something in the Arduino console window, I can see the led flash, but that text doesn’t come up on the Anroid app. And when I send text from the Android, nothing happens, no flash of the LED or anything.

    I’d really appreciate your help! Please email me or post here. cheers!
    David

  2. David says:

    For anyone who had the same problem as me, I managed to solve it. I used this Arduino code instead:
    /***********************
    Bluetooth test program
    ***********************/

    int incomingByte;

    void setup() {
    pinMode(53, OUTPUT);
    Serial.begin(115200);
    }

    void loop() {
    // see if there’s incoming serial data:
    if (Serial.available() > 0) {
    // read the oldest byte in the serial buffer:
    incomingByte = Serial.read();
    // if it’s an r, turn the LED on then off
    //ERROR: incomingByte can be any letter, the if statement is always true!
    if (incomingByte == ‘r’) {
    digitalWrite(53, HIGH);
    delay(500);
    digitalWrite(53, LOW);
    }
    }
    delay(250);
    }
    ———————————————————————
    Then using bluetooth mate Gold attach the Rx to the Tx on your arduino, and the Tx to the Rx on Arduino.

  3. dan says:

    I was able to get this to run only after separating the calls to
    findBT();
    openBT();

    Otherwise, mmSocket.connect(); throws an exception, “Service discovery failed”

    but if I put findBT() in onCreate() and just use the button for openBT(); it works fine.

    Or, if I make a second button, one for each, it works fine.

    Suggestions?

  4. dan says:

    oops, the problem was not what I thought, the two routines do not need to be separated. The actual issue is that I had to replace this code:

    Set pairedDevices = BluetoothAdapter.getBondedDevices();
    if(pairedDevices.size() > 0)
    {
    for(BluetoothDevice device : pairedDevices)
    {
    if(device.getName().startsWith(“FireFly-“))
    {
    mmDevice = device;
    Log.d(“ArduinoBT”, “findBT found device named ” + mmDevice.getName());
    Log.d(“ArduinoBT”, “device address is ” + mmDevice.getAddress());
    break;
    }
    }
    }

    with this:

    Set pairedDevices = mBluetoothAdapter.getBondedDevices();
    mmDevice = mBluetoothAdapter.getRemoteDevice(“00:06:66:46:5A:91”);
    if (pairedDevices.contains(mmDevice))
    {
    statusText.setText(“Bluetooth Device Found, address: ” + mmDevice.getAddress() );
    Log.d(“ArduinoBT”, “BT is paired”);
    }

    where I entered the address of my Bluetooth device.
    The original code finds the device and returns the correct address, but
    mmSocket.connect();
    generates an exception “java.io.IOException: Service discovery failed”

    Suggestions?

  5. vikaspandey says:

    hey can u post code to connect arduino to bluetooth dongle?
    thank you in advance.

  6. Bill says:

    Thanks for the great tutorial! I’m happy I found your blog. Somebody posted a link to it on stackoverflow.com

  7. gagi says:

    I am able to send from arduino Android and data goes fine. I am not able to send from Android to Arduino. Any ideas? I tried multiple pins 2,3 / 6,7 / 14,15 … for input and output

  8. matthew says:

    If anyone is having is having trouble with the Android programming, my pfodApp handles all that side. see http://www.pfod.com.au for full examples of a Arduino bluetooth controlled devices from Andriod, No Android programming required. User interface fully controlled from the Arduino device.

    • adolescent says:

      Hi, I can see you have vast experience in this area. But to use it needs to be purchased. We are here for fun or hobbyist, can you please help with the code posted here which isn’t working properly? Thanks in advance

  9. Folopes says:

    is this comunication possible through Duemilanove Bluetooth and App Inventor aplication?

  10. Ravi Shankar says:

    can any one tell me how to use the android code in it?

    how can I run the android code???

  11. rickin says:

    Hi, I got this working for code to be sent from android to arduino. But I cannot receive anything typed in the Serial monitor. The android text field doesnt show (accept) receive messages from the keyboard? Any ideas?

    • Kashyap says:

      hey! I am facing the same problem.. i can’t get the android text field to display (accept) receive messages from the keyboard..

      any suggestions?

  12. C.A Majdi says:

    Hi, can you make tutorial on android received serial data from arduino to android only? Any serial print on arduino will be display on android? Please….

  13. wawawuwewo says:

    Hye my name is Nur im student from Malysia i wanna asking u how to build a coding to interpret the data from arduino to android, im currently on my way done my underposgraduate prjoject the tittle is Monotoring Wireless CCTV’s Using Smartphone ( Android Application ). So anyone please help me about doing the coding 😦

  14. […] I have seen people doing projects with a system almost identical to what I would want to do, such as this one, as well as blogs devoted to the subject as a whole, found here. I plan on starting to sort through […]

  15. Elena says:

    What’s up to every body, it’s my first go to see of this webpage; this webpage includes
    awesome and truly excellent data designed for readers.

  16. ganesh47 says:

    Hi, I have small problem in sending data to printer via bluetooth. I am able to connect to printer and also When I send the data the LED in printer is stops blink and makes standard that means it is connected but when I try to send data to print it was unable to print the data. I dont know why it has happended and this is my code I have used and called on button click event. Please tell me if I was wrong at any step of calling. http://pastie.org/6172920

  17. Krunal Panchal says:

    Hello, I’m trying to send accelerometer data from android to pc through bluetooth…
    please help me……mail me on krunal_717@yahoo.co.in

  18. […] help me get started with the Bluetooth communication I have used the following tutorial: ANDROID AND ARDUINO BLUETOOTH COMMUNICATION And for the color selector I found this great AmbilWarna Color Picker together with a tutorial on […]

  19. […] researching how to get the devices communicating, there are many different tutorials out there; but it was this android-firmata project I ended up basing most of the code on. Firmata […]

  20. […] with the former (could get the Bluetooth module into command mode using ‘$$$’). https://bellcode.wordpress.com/2012/01/02/android-and-arduino-bluetooth-communication/ Followed this afterwards. Couldn’t get the code working on Android. I also don’t like […]

  21. hadjrami says:

    Hello

    I just get started with android and I need some help to integrate this application in a project where I am testing Bluetooth connectivity with android device.
    thank you in advance for your help.

  22. Craig Turner says:

    Hi, Many thanks for this tutorial. I used the instructions and recycled the BT code in my Relaxino app here:

    http://gampageek.blogspot.co.uk/2013/04/chillout-with-relaxino-heart-app-few.html

  23. Achilles Peeters says:

    Hi, I’m building an application to send and receive data (commands) to a bluetooth module. For the sending part i only had to change the name of the device (in the program) but here come’s the question:

    Anyone got somme suggestions / solutions / reference for import data into the android app from the bluetooth and display / save it temporarily ?

    IT WOULD BE A GREAT HELP !!

    thanks !
    Achilles Peeters
    achillespeeters@gmail.com

  24. […] Android and Arduino Bluetooth communication – guide to connect an Android tablet to Arduino Uno board using the Bluetooth module; […]

  25. I relish, cause I found just what I was taking a
    look for. You’ve ended my 4 day lengthy hunt! God Bless you man. Have a nice day. Bye

  26. Magnificent goods from you, man. I have understand your stuff previous to and you are just too wonderful.
    I really like what you have acquired here, certainly like what you’re saying and the way in which you say it. You make it entertaining and you still care for to keep it sensible. I can not wait to read far more from you. This is actually a tremendous website.

  27. lucky says:

    why it is not working on the latest adt. i encode the program and compile it and send it directly to my s4. When i click the open button it crashes.

    • same here, have you found the solution?

      • Raju says:

        First start your bluetooth and then press open then it will connect to your bluetooth module,otherwise app will crash if you click on open without enabling bluetooth of your android.
        For this reason i have changed code a littile bit by first checking whether android’s bluetooth is enabled or not…if it is enabled then only it will execute code written for opn button otherwise i’ve showed enavle bluetooth message in toast

  28. Andres Añez says:

    Hi matt, could you please help me?? I’m trying to implement the connection and sending code, but inside a surfaceview. Inside the canvas I’m simulating a joystick wich controls an arm (like those machines where you pick a toy), But I’m stuck with the bluetooth connection, so I found your tutorial and though maybe you could help me, please mail me at pabloandres84@gmail.com. At the end i’ll gladdly share my results.

    Appreciate your help and time

  29. zmd says:

    Greetings, I’m new to Arduino but not to embedded controllers. I need help purchasing the correct material to do the following:
    1. Bluetooth keyboard to communicate with the Arduino (the rii mini looks good)
    2. Arduino to control pneumatic valves 12v (4 relays needed)
    3. Arduino to control pneumatic flow controller (using a servo or a Low RPM dc motor – the servo is not going to do it unless modified to turn more than one turn)
    4. Some kind of encoder to get some feedback on the position of the pneumatic flow controller.
    5. Proper enclosure or a box to contain it neatly

    Ease of getting it done has more priority than prices.

    Please advise.
    Thank you in advance and best regards

  30. christopher says:

    the part about the UUID was a big help. thanks a lot.

  31. prerana says:

    hello Matt,I used your code and it helped me a lot.I extended it to receive continuous hex data and to save it in text file by creating arraylist. But when I try to find arraylist size or anything related to index,its not working.Why it is so???

  32. prerana says:

    @Matt, please help to write code for receiving data in hex format.
    Thanks in advance.

  33. Hi there colleagues, nice piece of writing
    and good arguments commented here, I am really enjoying by these.

  34. Hey dude… i just wanted to say thank you… it really helps me to understand…

  35. Oh my goodness! Awesome article dude! Thank you so much, However I am going
    through issues with your RSS. I don’t know why I can’t subscribe
    to it. Is there anybody else getting similar RSS issues? Anyone who
    knows the solution can you kindly respond?
    Thanks!!

  36. Les says:

    Have problems with Eclipse and these lines of code:

    Set pairedDevices = mBluetoothAdapter.getBondedDevices();
    if(pairedDevices.size() > 0)
    {
    for(BluetoothDevice device : pairedDevices)
    {
    if(device.getName().equals(“MattsBlueTooth”)) //Note, you will need to change this to match the name of your device
    {
    mmDevice = device;
    break;
    }
    }
    }

    1. ECLIPSE is not happy as I can not specify if ‘mmdevice’ is either local variable or filed or parameter

    2. Eclipse needs ‘Set’ specifies options are Set or Infer Generic Type arguments.

    3. Eclipse is not happy with pairedDevices

    I would be grateful for any help, many thanks

  37. Craig Turner says:

    Ok, I see the problem the webpage removes the text “” after Set.

  38. Les says:

    Do you mean like this ->

    Set = btAdapter.getBondedDevices();

    But it still shows an error “pairedDevices can not be resolved to a type”

    What attributes / declaration should it be given ?

    Thanks for your assistance.

  39. Les says:

    Typo error on last posting

    Set = btAdapter.getBondedDevices();

  40. Les says:

    Very odd What I type into “Leave a Reply” is getting garbled

    I have like this, it still errors

    Thanks

  41. Haris says:

    Kindly ensure pairing the device explicitly from your Android phone’s settings. Usually the pair code is 1234. The Hardware Tx,Rx pin are preferred if free on the Arduino

  42. Luis Perestrelo says:

    Hello,

    Honestly, I have never even programmed in Java before, however, I do know a lot of C and with a little bit of research I could fully understand your code.

    However, I get “Application has stopped” when I try to click the Open button. Even though I understand your code, I am quite newbie in Android Programming and I can’t fix the problem.

    Someone mentioned earlier that this doesn’t work on the newest adt. How do I fix this?

    Regards

  43. -Tap the weather control twice to get the clouds again, and once the
    clouds appear, tap the left cloud to get the rain.
    It is the high HTML5 Performance level that the developers are creating games for the gamers to play for absolutely free and this is possible
    without compromising with the quality. The kiosk’s information also draws
    feeds of reviews to display, so the user can see what other people thought
    of the item. Unless you are desperate to be up to appointment, you must perhaps
    pass the time pro the i – Pad 3, or pro a money off on the i – Pad 2, which
    will probably occur by approximately top as this brand extra
    manufactured goods has been on the promote pro a while.

    Awesome graphics bring forest, dessert, jungle, dungeon and mountain environments alive in more than 1,200 quests.

  44. Good day! Do you know if they make any plugins to help with SEO?

    I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good gains.
    If you know of any please share. Appreciate it!

  45. What’s up, yup this piece of writing is in fact pleasant and I have learned lot of things from it about blogging.
    thanks.

  46. Nice post with great details. I really appreciate your idea. Thanks for sharing.

    http://www.imobdevtech.com/HireDevelopers/Hire-iPhone-app-developer

  47. Harry says:

    Excellent Job ! Using your code I got bluetooth working in 10 minutes. I am usung a cheap serial converter from ebay. Thanks a lot !

  48. Abraham.Rubio says:

    I cannot download the source code

  49. Radeon says:

    Hello

    Why my app crash when i press any button?

    I have android 2.2 Froyo.

    Please help ty

  50. Steve says:

    This may seem like a trivial question, but I am unable to find a easy answer (step 1, step 2, ect). I installed BT Serial Tester from the Google Play Store and am able to run the app. I get BT paired but not BT connected. What I get is “Need BLUETOOTH_ADMIN”. I googled on how to edit the manifest, but all the explanations just confuse me.

  51. thomas says:

    halo i have question for you for example if i want to send the data depend on the option button i have chosen (example i have chosen close button ) so i want to send the word close to bluetooth module device connected to arduino what should i write the my application

  52. thomas says:

    for example look at the picture below for example i have chosen close button and i want to send the information close to another bluetooth device how can i do

  53. Mirron Panicker says:

    hi brohs, i m a newbie in arduino. My task was to built a small circuit in which when a pushbutton is pressed, my bluetooth (HC 05) would send a message to the serial monitor … Everything worked fine…. but i didnt get the message on serila monitor .. plz help me…. upload a code for me. This is ma code:

    #include

    const int buttonPin= 2;
    const int ledPin=13;
    int buttonstate=0;

    SoftwareSerial bluetooth(10, 11);

    void setup()
    {
    pinMode(ledPin, OUTPUT);
    pinMode(buttonPin, INPUT);
    //Setup usb serial connection to computer
    Serial.begin(9600);
    delay(500);

    //Setup Bluetooth serial connection to android
    bluetooth.begin(115200);
    bluetooth.println(“hai how u”);

    }

    void loop()
    {
    buttonstate= digitalRead(buttonPin);

    if(buttonstate == HIGH)
    {
    //Read from bluetooth and write to usb serial

    if(bluetooth.available())
    {
    char toSend = (char)bluetooth.read();
    Serial.print(toSend);
    digitalWrite(ledPin, HIGH);
    }
    }

    else
    {
    digitalWrite(ledPin, LOW);
    }

    }

  54. Juri says:

    Hello all of you that have had problems with sending data from Arduino serial monitor to the Android app.

    Look here!

    You need to set the right ASCII value.
    Set the ASCII value to ex. a space (val = 32), its the variable delimiter in method beginListenForData().

    void beginListenForData() {

    final Handler handler = new Handler();
    final byte delimiter = 32;

    Then when you send a message in the serial monitor in Arduino IDE you write the string you want and append with a space, ex.: “Arduino alive ” (without the “”). Now you should see the message Arduino alive in the Android application.

    Regards,
    Juri

    • Juri says:

      Another thing is that I have changed ONE line in the Arduino code.

      Original;

      //Read from usb serial to bluetooth
      if(Serial.available())
      {
      char toSend = (char)Serial.read();
      bluetooth.read(toSend);
      }

      TO;

      //Read from usb serial to bluetooth
      if(Serial.available())
      {
      char toSend = (char)Serial.read();
      bluetooth.write(toSend);
      }

  55. cirineu says:

    ​see my project with interface Serial arduino bluetooth android: https://www.youtube.com/watch?v=fUQlCDSy8KM

  56. gilremon says:

    Hi,

    I am having issues with:

    mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);

    which is throwing a Null Point Exception. I am using the suggested UUID and havent changed any in the code. What might be the problem?

    Thanks,

  57. gilremon see my project https://www.youtube.com/watch?v=fUQlCDSy8KM, everything all about interface arduino bluetooth android

  58. Joe Guerra says:

    Great, so I guess you can use the serial monitor to check for incoming messages from the tablet to the arduino? I’ll give the code a test run.

  59. Joe Guerra says:

    I’ve got it working one way, from the arduino to the android. Can’t get text sent from the android to arduino. (I’m using a bluetooth serial monitor on the android).

  60. Tecbot says:

    I managed to make all possible communications with bluettooth with Arduino via my Android phone, see everything in my video, I am providing source code, however I need access to my fanpage: https://www.facebook.com/EngebotCirineu? ref = hl, assimque I hit 500 likes.

  61. gampageek says:

    Thanks to Matt’s code I was able to control an Eight relay board with my Android tablet. So Iwanted to share this with you:
    http://gampageek.blogspot.co.uk/2014/12/android-arduino-controlled-eight-relay.html

  62. […] I can control a relay from an Android smartphone using Arduino and Bluetooth as seen here. […]

  63. arun hooda says:

    the code works fine except for the following two issues:

    1) connect the device via its mac address rather than it’s name..how to do it:

    REPLACE THIS CODE IN THE PROG

    Set pairedDevices = BluetoothAdapter.getBondedDevices();
    if(pairedDevices.size() > 0)
    {
    for(BluetoothDevice device : pairedDevices)
    {
    if(device.getName().startsWith(“FireFly-“))
    {
    mmDevice = device;
    Log.d(“ArduinoBT”, “findBT found device named ” + mmDevice.getName());
    Log.d(“ArduinoBT”, “device address is ” + mmDevice.getAddress());
    break;
    }
    }
    }

    with this:

    Set pairedDevices = mBluetoothAdapter.getBondedDevices();
    mmDevice = mBluetoothAdapter.getRemoteDevice(“00:06:66:46:5A:91″); ///(find the mac //add of ur arduino and replace it with that)

    if (pairedDevices.contains(mmDevice))
    {
    statusText.setText(“Bluetooth Device Found, address: ” + mmDevice.getAddress() );

    }

    2) then replace the delimiter with a space.this will solve your transmitting problems from arduino to android:

    void beginListenForData() {

    final Handler handler = new Handler();
    final byte delimiter = 32;
    ……..}

    with these changes made, the code works correctly .I have tested it both ways. 🙂

    for a complete beginner :

    https://developer.android.com/training/basics/firstapp/index.html
    go to this site and take lessons upto “starting a new activity”

    that will help a lot with the android side of things.

    thanks to matt bell and other users who helped with the issues

  64. Dip says:

    I am using a bluetooth printer and cardreader with your code.Printing is going well but when i am reading a magnetic i am sending a command to initialise the card reader via outputstream when socked is opend.Then swaping card produce no data instaed I get the old swaping data when i reconnect the device.

  65. Pratik says:

    I M able to send data to serial but unable to recieve it on my android device

  66. yazan says:

    hey
    but i want convert the value from char to int i dont know how please help me

  67. Prasad says:

    Hie,
    I m not able to receive file if my phone is locked only happens for anroid lolipop version . can anybody help me?

  68. Sadanand says:

    find the code given in below link and troubleshooting techniques and circuit diagram

    http://knowledge-cess.com/arduino-android-interfacing-example-code-and-troubleshooting/

  69. Prerana says:

    I tried this code as it is and it works perfect. Now I’m trying this with multiple commands like on 1st command i.e “1” it should give say (125),on command “2” it should give (125,256) and so on.

    I’m ready with arduino code and I’ve tested it with multiple bluetooth terminals which results perfect.

    But my Android code behaves weird.
    On every 1st command it reads perfectly but on every next commands it reads symbols in between, for eg. (0,����������316,312)

    Please help!!

  70. Wafi Azmi Hartono says:

    Thank you very much for your tutorial 🙂

  71. Kevko says:

    Is it only me or is there a 404 Error on the Sourcecode link?

  72. Sneha says:

    given link of source code is not working. Can you please provide another link?

  73. Sneha says:

    I have a bluetooth 4.0 and arduino uno r3. I have LM 35 temperature sensor. Now i want to read temperature sensor data into app. I am unable to do this.

    Can you provide a sample code for it with arduino and android both code?

    Its really urgent and helpful for me. please give me reply as soon as early.

    • Dorg says:

      I need nearly exactly the same code like you. I also have to get sensor data and show it in my android app.

      Were you able to solve this problem up to now?

  74. zdoucha says:

    Hello, this is my first arduino project: sending a file (jpeg, pdf, txt) from an arduino sd card module to android phone using arduino uno and bluetooth module HC-05

    have you any suggestion about the android app to receive the file ?
    thank you

  75. […] also see dan’s two consecutive comments on this thread: […]

  76. OKBET says:

    Good article and explanation.
    win a ride philippines

  77. […] Android and Arduino Bluetooth communication – guide to connect an Android tablet to Arduino UNO board using the Bluetooth module; […]

Leave a reply to Les Cancel reply