Arduino side program creation
Welcome to this new tutorial, In our new installment we are going to learn how to create a connection between our smartphone (Android) and our Arduino board. I don't hide from you that the first times I used this code it often gave me some problems, but don't be scared, after all this code once understood is very simple.
Also remember that to work all this we need a bluetooth module such as the HC-05 module.
Since we are in an Arduino tutorial, let's start immediately with the code side that concerns it. First we need to declare the Softwareserial library,
#include <SoftwareSerial.h>
this library allows us to create serial connections on digital pins, and also allows us to create more connections with a baud of 115200.
We continue with going to declare the constructor function and as a parameter we pass it 2 values, which are respectively RX and TX of our communication.
SoftwareSerial mySerial (52.53);
As previously said, we can also use digital Pins as if they were communication, unfortunately not all Pins are accepted. (Link to find out which Pins are accepted).
We will do all this in the global part of our sketch, but now we will focus on the individual functions. Let's start (Personal jargon synonymous with let's start) with the setup function.
void setup () { pinMode (key, OUTPUT); // key for bluetooth is used to configure it pinMode (btLed, OUTPUT); // notify that something has been received digitalWrite (key, HIGH); // activate key but only needed in the initial phase
In the setup we simply go to declare some Pins for the key (or Wakeup) and the btLed. The Pin key is generally used to enter AT mode (enter AT mode and commands) so as to be able to configure our bluetooth module. Instead, the Pin assigned to the btLed variable is a Pin that will be connected to a LED that will light up every time our board receives information via bluetooth.
We also create a serial communication at 38400 baud (but it can be created at different baud), both for the serial monitor and for the bluetooth communication.
// serial port initialization by defining the baud Serial.begin (38400); Serial.println ("Type AT commands!"); // SoftwareSerial "com port" mySerial.begin (38400); }
Moving on to the loop function the logic is very simple, a check is made on the myserial variable or on the bluetooth checking if it is available.
If the bluetooth is available it means that it is receiving information, then Arduino turns on the led above and enters a while loop to acquire the received value, this happens because our bluetooth receives the information byte by byte, then it reconstructs the command (or string) received by adding characters.
if (mySerial.available ()) { digitalWrite (btLed, HIGH); while (mySerial.available ()) { // I read the values received from the bluetooth command + = (char) mySerial.read (); }
the second If in our function is used to send commands through our card. this if is mainly used to send AT commands to configure the module, but it can also be used to send parameters to our device.
// send the input written by the user if (Serial.available ()) { delay (10); // The DELAY! mySerial.write (Serial.read ()); }
This code is usable with bluetooth such as HC-05, built to receive and send strings, but also with bluetooth modules such as XS3868, built for sending and controlling music.
Program creation on the Android side
In this second page we are going to create the Android application to communicate with our board. Specifically we will see how to communicate with the bluetooth module and what changes will be made in the various files created by our IDE.
To create our application we will use, as development environment, the official IDE of mom google or Android Studio (Download Android Studio).
A small premise will not show you how to create a new project with this IDE, since I assume that you already know the basics of this software.
First we create a new project in android studio and we create it with the Blank Activity (with the blank screen).
once the project is created, we go to the configuration file called AndroidManifest.xml and here we will add the following lines inside the manifest tag.
<uses-permission android: name = "android.permission.BLUETOOTH" /> <uses-permission android: name = "android.permission.BLUETOOTH_ADMIN" />
These lines give the permissions to our application to be able to interact with the bluetooth module that is present on our device.
Now let's move to the interface and insert a toggleButton inside our app. this button will allow us to connect our device with the bluetooth module connected to Arduino or to an equivalent board.
Once we have placed the toggleButton we go to the MainActivity.java file and declare the following libraries
import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import java.io.IOException; import java.io.OutputStream; import java.util.UUID;
below inside the class we are going to declare the following variables
// for bluetooth public UUID uuid = UUID.fromString ("00001101-0000-1000-8000-00805F9B34FB"); BluetoothAdapter mBluetoothAdapter = null; BluetoothSocket mmSocket = null; BluetoothDevice mmDevice = null; OutputStream outStream;
Now to connect to bluetooth we create an event of the toggle button inside the onCreate function, the event in question is the setOnClickListener.
// event: tap on the togglebutton for the bluetooth connection tgb.setOnClickListener (new View.OnClickListener () { public void onClick (View view) { if (tgb.isChecked ()) // check that the toggle button {is active mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter (); if (mBluetoothAdapter == null) // check if the devices are supported { // BLUETOOTH IS NOT SUPPORTED Toast.makeText (MainActivity.this, "BlueTooth not supported", Toast.LENGTH_LONG) .show (); tgb.setChecked (false); } else { if (! mBluetoothAdapter.isEnabled ()) // check if devices are enabled { // BLUETOOTH IS NOT ENABLED Toast.makeText (MainActivity.this, "BlueTooth not enabled", Toast.LENGTH_LONG) .show (); tgb.setChecked (false); } else { // BLUETOOTH IS ENABLED mmDevice = mBluetoothAdapter.getRemoteDevice (<MAC>); // MAC address of the arduino bluetooth try { mmSocket = mmDevice.createRfcommSocketToServiceRecord (uuid); } catch (IOException e) { tgb.setChecked (false); } try { // CONNECT THE DEVICE VIA THE mmSocket SOCKET mmSocket.connect (); outStream = mmSocket.getOutputStream (); Toast.makeText (MainActivity.this, "ON", Toast.LENGTH_SHORT) .show (); // bluetooth is connected } catch (IOException closeException) { tgb.setChecked (false); try { // TRY TO CLOSE THE SOCKET mmSocket.close (); } catch (IOException ceXC) { } Toast.makeText (MainActivity.this, "connection failed", Toast.LENGTH_SHORT) .show (); } } // CLOSE the isEnabled else } // CLOSE the else of mBluetoothAdapter == null } // CLOSE if (tgb.isChecked ()) else { try { // TRY TO CLOSE THE SOCKET outStream.close (); mmSocket.close (); } catch (IOException ceXC) {} } } // CLOSE public void OnClick (View view) }); // close the tgb.listener
All the explanations of what this function does is written in the comments between the code, but now I'll show you how to write something in the connection stream between the bluetooth. Everything is based on a very simple function, it will have to be called up if, once the bluetooth is connected, you want to transfer information.
private void sendMessageBluetooth (String message) { if (outStream == null) { return; } byte[] msgBuffer = message.getBytes (); try { outStream.write (msgBuffer); } catch (IOException e) { Toast.makeText (MainActivity.this, "Message Not Sent", Toast.LENGTH_SHORT) .show (); } }