Android MIT App Inventor – Auto Connect To Bluetooth

In a previous post I showed how to connect an app inventor Android app to a Bluetooth module connected to an Arduino to control an LED. See Turning a LED on and off with an Arduino, a HC-06 and Android

A few people have asked how to make it so that the app auto-connects to the Arduino on start up and I thought I would offer my solution. This example adds to the previous guide.

The easiest way to add an auto connect would be to use a fixed address and put the connection function call in the Screen1.Initialize block. Since the Screen1.Initialize block runs automatically when the app is started, the app would try to make the connection every time it started.
appInventorScreen_001
This is quick and easy but it means the mac address for the BT module is hard coded in to the app and to change the address you would need to change the app and recompile. This makes it very difficult to use a different Bluetooth module.

A better way is to allow the user to connect to any BT module and then save the address for next time. Then, when the the app is run again it can use the saved address to auto-connect to the Bluetooth module. By saving the address every time a new connection is made the user can change Bluetooth modules with ease.

The App

The first time the app is run there is no saved address and the app waits for the user to make a connection.
– Click the BT button to bring up a list of paired devices.
– Select one of the paired devices, in my case the HC-06.
– If the connection is successful the BT button changes to “Connected”.
– The address of the connected BT device is displayed on screen.
ScreenShots_01

The next time the app is run it will try to auto-connect to the saved device.
– While trying to connect the BT button will display “Connecting”.
– If the connection is successful the BT button will show “Connected”.
ScreenShots_02

App Designer Screen

designerScreen_001

There are only a few screen elements to note:
A button to activate the connection process.
A label to show the saved address.
The LED button to turn an LED on or off.
A list to store the list of paired devices.

The non-visible components required are:
TinyDB.
Clock1.
And of course the Bluetooth client.

The Blocks

Android MIT App Inventor - Auto Connect To Bluetooth_blocks_001

The Main Details

Blocks001_Screen1_Initialize
When the app starts, the Screen1.Initialize function is called. This retrieves the saved Bluetooth address from the TinyDB and copies in to the global variable “savedDeviceAddress”, it then starts the timer. If there isn’t a saved address the variable is set to “” and the timer is not started.

I use a timer to overcome a minor annoyance caused by how app inventor works. If the connection blocks are all placed in the Screen1.Initialize function, the connection process works but the screen is not updated correctly and the “Connecting” button text is not displayed.

Blocks002_Clock1_Timer
When the timer fires, the Clock1.Timer function is called. It is here the app tries to connect to the saved Bluetooth address. If a connection is successful the BT_BUTTON text is changed to “Connected”. If the connection is not successful an error message is displayed. The function also checks that Bluetooth is turned on before trying to make a connection.

The BT_BUTTON allows for new connections, when it is clicked it activates the list picker and allows the user to select another device. When a new connection is made the mac address of the newly connected BT module is saved to the TinyDB.
Blocks002_BT_BUTTON
Blocks002_ListPicker

The rest of the code is the same as the previous example. For further details see Turning a LED on and off with an Arduino, a HC-06 and Android

 

Download

Download the app inventor aia file

 
 

94 thoughts on “Android MIT App Inventor – Auto Connect To Bluetooth”

  1. Thank you for your help.

    When the connection to the phone is lost, not appear a warning message “lost connection” or the button not change “not coonected”, when I move back into range … must reconnect manually.
    Is possible checking every second, whether the device is in range or not? And auto connect when is in range.

    Reply
    • At the moment I don’t believe this is possible with MITs app inventor. It may be possible if using Eclipse or Android Studio but I have only used app inventor and know nothing about JAVA.

      You can test for an active connection by sending a “are you still there” message. If the Arduino replies then everything is good. If the Arduino does not reply (you will also get a system error) then the connection has been lost and the connection can be closed. However, you would need to manually reconnect once the connection was closed.

      I will look into this further but I think it will be a long term project and not something I can do in a day or two. If I find anything on the net I will post links.

      Reply
          • How to do that “trapping connection” sir?
            Sorry It been a long times, but i stuck to get the answer how to reconnect bluetooth to android smartphone if it got disconnect sir.
            So how to checking connection every second (or atleast 5-10s) And auto reconnect when is in range.

            And honestly i never used android studio because my laptop maybe couldnt handle it & i only could read java (even need sometimes) or lets say i lack of java. So mit app inventor is my best solution :D

            Thank you sir, all ur tutorials really help me a lot :D

            Reply
      • Hello, sir. maybe this could be the answer :

        https://youtu.be/HmA9g3y3O0k

        but when I dissected this, I got confused because it was made for a project to run an automatic motorcycle.

        can you simplify this reference with an LED?

        if in range the LED will automatically turn on, and if out of reach the LED will automatically turn OFF by utilizing the HC05 module’s automatic connection function with a smartphone.

        Reply
  2. Is possible that the arduino sent the data permanent to phone? like this:
    int LEDState;
    void loop()
    {
    ………..
    ………..
    LEDState = digitalRead(LEDpin);
    Serial.println(LEDState); // with BTserial.print(LEDState) don’t work …
    }

    I don’t know, how can I make, when the phone not receive “1” OR “0” appear the warning message, and the BT button have the function like at startup (connecting mode).

    Sorry for my poor English.

    Reply
    • Hi Saua,

      it is possible but would need a fair amount of work to add to the above example.

      This example, and also the LED on/off example, are basic “send data to the Arduino only”. I don’t have anything to show at the moment. You can take a look at https://www.martyncurrey.com/arduinobtcontrol/. This partially does what you what but not exactly.

      I am working on an Arduino monitor app but this is going to be a while before I have anything I can post.

      Reply
    • Assuming I understand correctly, you want to have the Arduino control the LED and then show the LED status in the Android app.

      This sketch is not really a good place to start if you want the Android app to display the LED status where the LED is controlled by the Arduino. The app was designed purely to send controls to the Arduino.

      To work the other way around you need to read the data from the bluetooth (you have done this but in the wrong place), if you receive a “1” set the background colour of the LED button to green and if a “0” set the background to red.

      To do this you need to use a timer (add a “when Clock1.Timer” block) not a button, and every time the timer fires check for new data, if you receive a “1” set the background colour of the LED button to green (call buttonON) and if a “0” set the background to red (call buttonOFF). Set the timer interval to something like 100ms.
      The timer should not be started until after you have made the bluetooth connection otherwise you will get constant errors.

      Since you are receiving data not sending, you can remove the LED_BUTTON_btn.click block.

      Reply
    • You need to have a button switch and an LED on the Arduino. When the switch is closed toggle the LED status and at the same time send a control code to the Android app. For example, “1′ for on and “0” for off.

      The Android app needs to receive the control code and then act accordingly. In the app, don’t change the existing functions, instead, add new ones. You will need to

      – add a timer. This is used to check for new data received over bluetooth. Do not start the timer until you have a bluetooth connection.

      – add a “when Clock1.Timer” block. Use this to check to see if there is new data.

      – if you have new data,
      – if it is a “1′ change the LED button to “ON”
      – if it is a “0” change the LED button to “OFF”

      Unfortunately I don’t have examples but the project looks interesting and I sure you will get it working.

      Reply
  3. Hello,

    I am trying to monitor 4 leds.
    The led’s are also connected to a switch. Therefore, when the switch is pushed, then 5V are passing through and the led is on. The android device should also display the change. Any leads how to transmit the data from one end to the other?

    Thanks in advance

    Reply
    • You need to monitor the pins the LEDs are connected to. When one of these goes HIGH (and the LED turns on) send a “LEDx is ON” command to the android app. When the pin returns LOW send a “LEDx is off” command. x is the LED number.

      Have a look at the earlier ai examples. These should help with how to send data.

      Reply
  4. dear sir,

    i have successfully auto connect the bluetooth,but is it possible with app inventor that when we open the app then if my bluetooth is not ON then one message box pop up and ask for turning on bluetooth.??
    if this possible ,please guide.

    Reply
  5. Do you by chance have any idea how do I notify the user whenever there is some data coming on the phones Bluetooth. Like I’ve several sensors in the house and I’ve to report about their triggering to the user, on the app. But then I do not want the user to continuously stare the app. Only when there is some trigger, he should open the app, and check. Could you help me find solution to this.

    Reply
  6. Super well done explanation.

    I have been struggling with this same concept for a long time in ai2.

    I am running a Climate control in a old honda.
    http://toddheffley.com/wordpress/?p=6942

    My particular problem is that the arduino/hc06 shuts off with the key switch. The tablet remains on its own battery. Next engine start requires re connect.

    Your example will solve most of that problem!

    I am already reporting the car’s voltage from the arduino/hc06 to the tablet. The field goes blank when the key is off.

    I was thinking that ai2 could watch that value, and when it goes blank AI2 could begin attempting a reconnect.

    Does that sound readonable?

    I sure do appreciate the effort you have put into this!

    Todd

    Reply
    • Since in AI you cannot tell when the connection is broken, this is basically how you check. Send data at a specific time period and if you do not receive the data it you know there is a problem.

      Remember that AI thinks it is still connected so you will need to disconnect first.

      I don’t have examples to post but it should not be too difficult to add a function that detects when there is not data and then disconnects and then reconnects to the Bluetooth module.

      .

      Reply
      • got it!

        1.The trick was to send data all the time from the arduino.
        2. in AI, test the incoming data field to see if it is empty.
        3.DISCONNECT the BT, even though it is already disconnected.
        4. reconnect to same connection.
        5. I error trapped the screen so that the nuisance errors would not take over the display.

        Thanks Marty

        Todd

        Reply
        • Hi Todd, can you please explain in more detail how your are able to auto reconnect to bluetooth? I am having difficulties in doing that.

          I would really appreciate any feedback. Thanks in advance.

          Sam

          Reply
  7. Hi,

    your tutorial is super helpful and informative. I’m currently trying to auto reconnect bluetooth after the HC-06 is turned off then on again. Do you have any tips that could be useful?

    Thanks in advance!

    Sam

    Reply
    • If you know that the connection is down, the easiest way is to manually disconnect and then reconnect.

      The issue with broken connections is that AI does not know when the connection is broken unless it tries to send data. If the connection is broken an error message is generated when it tries to send. You can use this error message in the app.

      My solution is to have a timed dummy send data function.
      If data has not been sent within the last second I send a dummy tag, if I get an error I know the connection is down. Using this method also keeps the connection active.

      Reply
  8. Hello,

    Your tutorial was really helpful! However, I do have a question.

    I was wondering how to auto-connect to the same BT module every time I run the app? Do I just hard code the address into the purple call Connect block and if so, how do I obtain the address for the BT module I want to use?

    Also would the address of the BT module change for any reason other than using a different BT module?

    Thanks!

    Reply
  9. HAI … WHAT CAN GIVE A LITTLE SAMPLE APP INVENTOR AUTO UPDATE RELAY (ARDUINO-APP INVENTOR), I HAVE ALWAYS TRIED BUT FAILED. THANK YOU

    Reply
  10. In order to use this app, the bluetooth of the android phone need to pair with the bluetooth module hc05 first right?

    is it possible to connect to a bluetooth device which have not been paired before using MIT app inventor 2?

    Reply
  11. hii..
    the problem i am facing is that on simultaneous and quickly touching the buttons the app stops responding.
    can you help me with this problem?

    Reply
  12. hi,
    So tried to working with MIT App Inventor and communicate two screen with single Bluetooth module. i am able to communicate Bluetooth in Screen 1 but in multiple screen it just disconnect from device.can you please help to initialize bluetooth module for multiple screen.

    request : can you please give your email for further communicate.

    Reply
  13. GREAT TUTORIALְ!!!
    I would like to ask if i can make an automatic rutin connections in intervals that connect alternatley between two hc device and the phone – so the goal is to receive from the two device a small data every 3 sec and to sum it together ! ?

    thank you in advanced !!

    Amit.

    Reply
  14. of course any other way to combine to device messages to one phone using app inventor will be another solution if you can tell me ..?

    Reply
  15. how can i achieve this block came from Procedures. the one below the Notifier1 AfterChoosing. pls show me how. thank you so much. hoping for your immediate reply

    Reply
  16. Need a little help.
    I can’t find the blocks “call buttonOFF” and “call saveConnectionAddress”.
    under which section i can find them?

    Reply
  17. how to coding arduino : if bluetooth paired/connected led turn off, if bluetooth disconnected than led turn on .

    Reply
    • A few different ways:

      1. Use a Bluetooth module with a STATE pin. When the module is connected the STATE pin goes HIGH. Either connect the STATE pin to a LED or connect to an Arduino pin and check the pin.

      2. Some Bluetooth modules have messages when connections are made and lost. Use one of these modules and then keep checking the data on the serial in.

      3. Have a regular dummy message sent from the remote device. I normally use 1 second or 2 seconds. While you are getting the messages the connection is active. No message means the connection is lost.

      Using a module with a STATE pin (HC-05 no HC-06) is the easiest to implement.
      If using a module that does not have a breakout board check the data sheet. One of the pins will act like the STATE pin.

      Reply
      • Thanks for your replay !

        in this case diferent :

        void loop() {
        while (BT.available()) //Check if there is an available byte to read
        { delay(10); //Delay added to make thing stable
        char c = BT.read(); //Conduct a serial read
        VOICE += c; } //build the string

        if (VOICE == “Honda off”) { lock();} // key lock use control
        else if (VOICE == “Honda on”) { unlock();} // key auto on if BT paired

        How to code if bluetooth disconnected and automatically locked without using control
        I am frustrated with this problem, I hope you can give an example of the code. Thanks for the help. greetings from Indonesia

        Reply
    • With Bluetooth Classic you can connect to only one Bluetooth module at a time. To make a network (or mesh) you need to connect to each node in turn. For example:

      Connect to node 1. Get data. Disconnect.
      Connect to node 2. Get data. Disconnect.
      Connect to node 3. Get data. Disconnect.

      Reply
  18. Hello, I really enjoyed your work. Could you send me the .aia file?
    If I may thank you very much …

    Congratulations on the post

    Reply
  19. Does this method avoid the annoying passcode request? I am using Listpicker with BluetoothClient1 Connect, etc and always must enter 1234 passcode prior to establishing the connection. I have other 3rd party apps that connect directly without the passcode. I have looked at the passwordtextbox, but not if that would do it. Any suggestions appreciated. Thanks.

    Reply
    • This should not be happening (unless there is a setting in AI2 that I am not aware of).

      With Bluetooth 2, connections are a 2 stage process:
      1 – pair
      2 – make a connection

      The Bluetooth device must be paired with the main device before you can make a connection. It is at this stage you must enter the pass code. You do thid with the device settings, not the app.

      After the devices are paired you can connect without entering the pass code.

      Reply
      • Martyn,
        Thanks for your response. When I click on the Listpicker, I get a new screen with the 4 Bluetooth devices that have been previously paired on my tablet. When I select HC-06 I then get the “Bluetooth pairing request” screen suggesting 0000, or 1234. There is no opt out. I looked in tablet Settings and the 4 Bluetooth devices are shown as being paired and there is no other menu available to set passcodes.
        John

        Reply
  20. Hello Martyn,
    As usual, above project is greatly helpful. I wanted to ask if we can sense two button press events at the same time using app inventor? i.e if I am pressing RIGHT direction key and simultaneously press UP in order to make my robot go diagonally?

    Reply
  21. Excuse me, I want to ask. whether the smartphone can establish an automatic connection with the arduino when close together, after the smartphone and bluetooth disconnected because of the distance., Thank you

    Reply
  22. Hi Brother
    I’m very newbie in Arduino and APP inventor world.

    I would like that my Android auto-connect to hc-06.

    I have paired the device, I can communicate (to and from arduino), but I have always to init the connection from my Android.

    I would like something look like the bluetooth headsets: whenever smartphone is nearby (in range) of bluetooth it will connect.

    Please Help Me…
    thanks in advance!

    Reply
  23. May I know how to sway the screen based on the value from the Bluetooth? In the other word, set a threshold value, if the value receive from Bluetooth is excessed, then, open another screen and will return back to previous page after a few second

    Reply
    • Because each screen has to have its own Bluetooth connection and you cannot share a connection across different screens I recommend using pseudo screens. This is where you hide and display elements to make it look like you are moving to a new screen. See https://www.martyncurrey.com/app-inventor-2-pseudo-screens/

      Then, when you receive the correct value from Bluetooth, display the new pseudo screen, hide the old screen, and start a timer. Set the timer for the delay you want, when the timer fires, stop the timer, hide the new screen and display the old screen.

      Reply
  24. HELO
    THIS IS GREAT APP. SIR I WANT TO KNOW ONE THING CAN IT POSSIBLE
    THAT WHEN BLUETOOTH CONNECTION GET LOST THEN CLOSE APP AUTOMATIC

    Reply
  25. thanks for your tutorial. can i receive data from two separate sensors and store the data in a file for further process.
    thanks

    Reply
  26. Hello,
    I have a question, is it possible in App Inventor 2 to receive coordinates on a app from an adafruit ultimate gps with arduino?

    Reply
  27. Hello, thanks for this great app. But when I generate apk for my phone the saved bluetooth address always stays none but it can store bluetooth addresses well on AI companion.

    Reply
  28. Hi I’ve tried to down the app but there’s an error message when I open the app could you assist me with this matter. Thank you

    Reply
  29. Hi, after downloading the file and opening it on mitappinventor it say that the project file is not a project source file . could you help me with this issue. Thank you

    Reply
      • Hi i have tried to upload the file that is inside the zip file but it still has the same message saying that the file is not a project source file

        Reply
        • sorry fore the late reply. Did you get this figured out?

          Tried uploading when I made the previous comment and just tried again. Both times it worked so I don’t know what the issue is, unless you are using the original app inventor or one of the non mit versions.

          Reply
  30. Hello Martyn i’m doing a school project and i am using a hm-10 bluetooth card. Is there a way than i can edit this program to work with the hm-10 bluetooth card ?

    Reply
  31. Hi Martyn, Very good concept on auto connecting to Bluetooth module. Can we hardcode Bluetooth name instead of MAC Id ? and Is their any way of checking the Bluetooth connection is active or lost.

    Reply
  32. Hi there, thanks for the tutorial, I have a BLE HC-06, so the commands dont work, I can use TinyDB to store the deviceName but there is no function to acquire deviceAddress. Any advice would be appreciated.

    Reply

Leave a Reply to petrouxs Cancel reply