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.
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.
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”.
App Designer Screen
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
The Main Details
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.
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.
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
arduinoBTcontrol_Basic_Saved_Connection
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.
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.
can we do that with time interval? when it disconnect, time interval active and try getting connection again.
This should be possible by trapping a connection error.
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
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.
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.
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.
These examples are also very helpful, thank you very much!
I want to change the color of the LEDbutton, depending on the LED status.
the arduino send “1” when the LED is on and “0” when is OFF
digitalWrite(LEDpin,HIGH);
BTserial.print(“1”);
……
I modified the aia file in this way, but don’t work.
http://kepfeltoltes.hu/150930/problem_www.kepfeltoltes.hu_.jpg
What could be the solution?
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.
Thank you for your answer, I’d like to do that:
https://www.youtube.com/watch?v=zUvN5WG-Peo&feature=player_embedded
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.
thank you very much for this example…..
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
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.
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.
It is possible by using the activity starter. See https://puravidaapps.com/snippets.php#2enableBT
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.
This is not something I have done.
If you have not already, join the ai2 forum at https://groups.google.com/forum/#!forum/mitappinventortest and ask there. You should get lots of help from the forum.
Hello,
I want to change the Bluetooth’s Name and PIN with app – appinventor.
please help me!
Hi,
to change the name and PIN you need to use AT commands and AT commands cannot be sent over the bluetooth connection. They can only be sent over the serial connection using the RX and TX pins. This means you need to use an Arduino (or something similar) to change the modules properties.
Thank you for your help!!
Hi
I am Korean.
So I can not use English fluency.
sorry.
How can I change the Bluetooth’s Name and PIN with Arduino?
take a look at https://www.martyncurrey.com/arduino-and-hc-06-zs-040/
You can also Google search Arduino + bluetooth + change name.
Thank you very much.
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
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.
.
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
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
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
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.
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!
HAI … WHAT CAN GIVE A LITTLE SAMPLE APP INVENTOR AUTO UPDATE RELAY (ARDUINO-APP INVENTOR), I HAVE ALWAYS TRIED BUT FAILED. THANK YOU
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?
this is not possible with BT v2.0/2.1. The BT module must always be paired before a connection can be made.
I have a bluetooth BLE HC-08,
How to program auto connect with my iphone ??
I have no idea :-(
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?
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.
app inventor does not share a Bluetooth connection across different screens. To get round this use pseudo screens. See https://www.martyncurrey.com/app-inventor-2-pseudo-screens/
hi Martyn,
I am so glad to see your reply.it’s totally a new idea for me & really helpful at least without nothing.
Now I have another problem,can you give any tutorial,like I want to send a value to my server & it will feedback me the total value i have send or sum value after reduce amount as I want.
Actually I want to make a app which can be used as payment system.
take a look at the other posts that cover BT communication.
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.
This is possible but beyond the scope of this guide. However, the above could be expanded to include more than one BT module.
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 ..?
Thanks again for your replay !
can you direct me were i can find it in the wed
and give me some guide-lines ?
is it only a procedure of duplicate the regular method of coding a BTCLIENT
to a BTClient1 and BTcLIENT2 ?
Amit.
how i can get coordinate of the robot that include(arduino +bluetooth module) on google maps
All I can suggest is you join the App Inventor forum and ask there.
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
is it possible to give the app as a download
The aia file can be downloaded above
Need a little help.
I can’t find the blocks “call buttonOFF” and “call saveConnectionAddress”.
under which section i can find them?
You cannot find them because there aren’t any…. See the blocks above.
how to coding arduino : if bluetooth paired/connected led turn off, if bluetooth disconnected than led turn on .
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.
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
The issue is that the Arduino does not know directly when Bluetooth is disconnected.
Either use a timeout, for example if not received anything for 5 seconds then the connection is broken, or, use an HC-05 that has a STATE pin.
Maybe I should find another way and with all due respect I thank you for all your help
Have you found a way?
please , how can i receive data from multiple bluetooth modules in same time ?
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.
Hello, I really enjoyed your work. Could you send me the .aia file?
If I may thank you very much …
Congratulations on the post
you can download the aia file from the link above.
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.
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.
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
Hi John,
I don’t recall ever getting this. Try posting the the AI forums. I am sure somebody there can help.
https://groups.google.com/forum/#!forum/mitappinventortest
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?
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
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!
I don’t believe you can get the HC-05 to act exactly the same as HID but it is worth searching online.
If using creating your own app look at the connect command. This will wait until the remote device is available. See https://developer.android.com/reference/android/bluetooth/BluetoothGattServer.html#connect%28android.bluetooth.BluetoothDevice,%20boolean%29
The downside is that the app needs to be running for this to work.
Hello Khanif
Have you found a solution to this issue? I’m looking for the same thing.
Thanks
Vander
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
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.
Martyn,
Great Tutorial Thanks!
gerat
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
thanks for your tutorial. can i receive data from two separate sensors and store the data in a file for further process.
thanks
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?
It is possible but you need to add something to transmit the data. Either over wifi or Bluetooth.
Can you creat this tutorial into a video, thanks
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.
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
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
upload the aia file that is inside the zip file.
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
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.
HI i have tried to download the file again and it works now . Thank you so much for helping me i really appreciate it.
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 ?
yes but it is not a simple swap. Have a look at the HM-10 and app inventor post https://www.martyncurrey.com/arduino-hm-10-and-app-inventor-2/. This does not include an auto connect but you should be able to figure it out.
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.
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.