I made this Bluetooth auto connect program a while ago for my HC-05 connected to my Arduino Nano, and it has been working great, so I thought I would share my code for anyone who may need it.
If anyone spots an error or has any suggestions to improve it, please let me know.
How it works:
The user dose need to select a device to connect to. You do not need to use a ListPicker or save any settings to a TinyDB database.
Simply enter the name of your Bluetooth module in the “DeviceName” variable in the ConnectBT code block, e.g.: HC-05, or HC-06.
If you are using an ESP32, enter the name you set your Bluetooth module to in your ESP code.
When you start your App, the Auto Connect will determine the status of your device and Bluetooth module and display the appropriate help or connecting box then automatically connect.
It is fully automatic and will automatically re-connect if the signal is lost or warn if power to your module is lost. It is also speech enabled, to warn the user when an error is detected, and includes a simple animated connecting progress bar.
How to test:
-
Unplug your Bluetooth module for a second, then plug it back in to simulate a lost connection.
The App should display a “Connection Lost” box, then automatically re-connect in a few seconds. -
Unplug your Bluetooth module and LEAVE it unplugged.
The App should display a “Connection Lost” box, then automatically try to re-connect.
When it detects that the module is NOT plugged in, it should display a "Your Bluetooth device is not turned on" box and continue trying to re-connect.
Plug in your module, it should automatically re-connect in a few seconds. -
Open your device settings and turn OFF Bluetooth.
The App should display a "Unable to connect. Bluetooth is not enabled." box.
Turn your device Bluetooth back on, the App should automatically re-connect in a few seconds. -
Open your device settings and un-pair your Bluetooth module.
The App should display a "Unable to connect. Your device is not paired." box.
Re-pair your Bluetooth module, the App should automatically re-connect in a few seconds.
Blocks:
AutoBtConnect2.aia (9.0 KB)
I hope someone may find this code useful.
Mike.