ArduinoBluethoth AndroidStudio
ArduinoBluethoth AndroidStudio
Click twice the TextView to change the text. A box will appear:
Text = The text to be displayed.
Id = the id of this widget
Click twice the Button to change the text. A box will appear:
Text = The text to be displayed.
Id = the id of this widget.
import android.widget.Button;
import android.widget.ListView;
Create widgets variables to “call” the widgets used to create the layout:
Button btnPaired;
ListView devicelist;
btnPaired = (Button)findViewById(R.id.button);
devicelist = (ListView)findViewById(R.id.listView);
import java.util.Set;
import java.util.ArrayList;
import android.widget.Toast;
import android.widget.ArrayAdapter;
import android.widget.AdapterView
import android.widget.AdapterView.OnClickListener
import android.widget.TextView;
import android.content.Intent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
Writing a stable code avoids weird erros, so it’s good to check if the device has bluetooth adapter
and whether it’s activated.
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if(myBluetooth == null)
{
//Show a mensag. that thedevice has no bluetooth adapter
Toast.makeText(getApplicationContext(), "Bluetooth Device Not
Available", Toast.LENGTH_LONG).show();
//finish apk
finish();
}
else
{
if (myBluetooth.isEnabled())
{ }
else
{
//Ask to the user turn the bluetooth on
Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon,1);
}
}
According to Android documents, an Intent is a messaging object you can use to request an
action from another app component. Although intents facilitate communication between
components in several ways, there are three fundamental use-cases:
To start an activity:
An Activity represents a single screen in an app. You can start a new instance of an Activity by
passing an Intent to startActivity(). The Intent describes the activity to start and carries any
necessary data.
To start a service:
A Service is a component that performs operations in the background without a user interface.
You can start a service to perform a one-time operation (such as download a file) by passing an
Intent to startService(). The Intent describes the service to start and carries any necessary data.
To deliver a broadcast:
A broadcast is a message that any app can receive. The system delivers various broadcasts for
system events, such as when the system boots up or the device starts charging. You can deliver a
broadcast to other apps by passing an Intent to sendBroadcast(), sendOrderedBroadcast(), or
sendStickyBroadcast().
We need to “listen” when the button is clicked to show paired devices. So OnClickListener Api
will handle it
btnPaired.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
pairedDevicesList(); //method that will be called
}
});
pairedDevices = myBluetooth.getBondedDevices();
if (pairedDevices.size()>0)
for(BluetoothDevice bt : pairedDevices)
else
devicelist.setAdapter(adapter);
This second layout will have three buttons, one TextView and a seekbar:
Indicator;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.AsyncTask;
import java.io.IOException;
import java.util.UUID;
We have to initialize the variables and retrieve the bluetooth device address got in DeviceList
class.
@Override
@Override
protected Void doInBackground(Void... devices) //while the progress
dialog is shown, the connection is done in background
try
BluetoothDevice dispositivo =
myBluetooth.getRemoteDevice(address);//connects to the device's address and
checks if it's available
btSocket =
dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a
RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
catch (IOException e)
return null;
@Override
{
super.onPostExecute(result);
if (!ConnectSuccess)
finish();
else
msg("Connected.");
isBtConnected = true;
progress.dismiss();
We need to “listen” when the button is clicked to write a command to turn on/turn off the led,
disconnect and the control of the brightness.
btnOn.setOnClickListener(new View.OnClickListener()
{
@Override
});
btnOff.setOnClickListener(new View.OnClickListener() {
@Override
});
btnDis.setOnClickListener(new View.OnClickListener()
@Override
});
brightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
if (fromUser==true)
lumn.setText(String.valueOf(progress));
try
btSocket.getOutputStream().write(String.valueOf(progress).getBytes());
catch (IOException e)
}
}
@Override
@Override
});
There is a method called msg(); This method calls Toast.maketext(); There's the method Called
Disconnect(); turnOffLed(); and turnOnLed();
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
private void Disconnect()
{
if (btSocket!=null) //If the btSocket is busy
{
try
{
btSocket.close(); //close connection
}
catch (IOException e)
{ msg("Error");}
}
finish(); //return to the first layout
}
private void turnOffLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("TF".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void turnOnLed()
{
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("TO".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
The manifest file presents essential information about your app to the Android system,
information the system must have before it can run any of the app's code.
This apk uses Bluetooth Adapter and it is not available in emulator, you must test it in a running
device, but before you have to add some users-permissions, otherwise the apk will crash.
char command;
String string;
boolean ledon = false;
#define led 5
char command;
String string;
boolean ledon = false;
#define led 5
void setup()
{
Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop()
{
if (Serial.available() > 0)
{string = "";}
while(Serial.available() > 0)
{command = ((byte)Serial.read());
if(command == ':')
{
break;
}
else
{
string += command;
}
delay(1);
}
if(string == "TO")
{
ledOn();
ledon = true;
}
if(string =="TF")
{
ledOff();
ledon = false;
Serial.println(string); //debug
}
if ((string.toInt()>=0)&&(string.toInt()<=255))
{
if (ledon==true)
{
analogWrite(led, string.toInt());
Serial.println(string); //debug
delay(10);
}
}
}
void ledOn()
{
analogWrite(led, 255);
delay(10);
}
void ledOff()
{
analogWrite(led, 0);
delay(10);
}
Step 9: Download
Thanks.