Android Bluetooth App
Hi i am kind of new to android development and have recently started working with bluetooth API. I was able to connect my phone to the HC-06 connected to my Arduino NANO. However, I am unable to transfer data correctly. My goal is to grab the current value from the device and store it in a variable in the application, and also display it. Here is my code for both arduino and app.
Android Studio
package com.clipius.clipiusweight;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
TextView myLabel;
TextView dataLabel;
EditText myTextbox;
BluetoothAdapter mBluetoothAdapter;
BluetoothSocket mmSocket;
BluetoothDevice mmDevice;
OutputStream mmOutputStream;
InputStream mmInputStream;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
int counter;
volatile boolean stopWorker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button openButton = (Button)findViewById(R.id.getDataB);
Button sendButton = (Button)findViewById(R.id.sendDataB);
//Button closeButton = (Button)findViewById(R.id.close);
myLabel = (TextView)findViewById(R.id.ConnectionCheck);
dataLabel = (TextView) findViewById(R.id.weightValueText);
//myTextbox = (EditText)findViewById(R.id.weightValueText);
//Open Button
openButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
try
{
findBT();
openBT();
}
catch (IOException ex) { }
}
});
}
void findBT()
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter == null)
{
myLabel.setText("No bluetooth adapter available");
}
if(!mBluetoothAdapter.isEnabled())
{
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if(pairedDevices.size() > 0)
{
for(BluetoothDevice device : pairedDevices)
{
if(device.getName().equals("HC-06"))
{
mmDevice = device;
break;
}
}
}
myLabel.setText("Bluetooth Device Found");
}
void openBT() throws IOException
{
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
beginListenForData();
myLabel.setText("Bluetooth Opened");
}
void beginListenForData()
{
final Handler handler = new Handler();
final byte delimiter = 10; //This is the ASCII code for a newline character // old 10
stopWorker = false;
readBufferPosition = 0;
readBuffer = new byte[1024];
workerThread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopWorker)
{
try
{
int bytesAvailable = mmInputStream.available();
if(bytesAvailable > 0)
{
byte[] packetBytes = new byte[bytesAvailable];
mmInputStream.read(packetBytes);
for(int i=0;i<bytesAvailable;i++)
{
byte b = packetBytes[i];
if(b == delimiter)
{
byte[] encodedBytes = new byte[readBufferPosition];
System.arraycopy(readBuffer, 0, encodedBytes, 0, encodedBytes.length);
final String data = new String(encodedBytes, "US-ASCII");
readBufferPosition = 0;
handler.post(new Runnable()
{
public void run()
{
dataLabel.setText(data);
}
});
}
else
{
readBuffer[readBufferPosition++] = b;
}
}
}
}
catch (IOException ex)
{
stopWorker = true;
}
}
}
});
Toast.makeText(getApplicationContext(), "Starting Worker Thread", Toast.LENGTH_SHORT).show();
workerThread.start();
}
}
Arduina
#include <SoftwareSerial.h>
int sensorPin = A0;
int sensorValue = 0;
char stringValue[5];
SoftwareSerial BTserial(10, 11); // RX | TX
void setup() {
Serial.begin(9600);
BTserial.begin(9600);
}
void loop() {
// Gets the int. value of the sensor
sensorValue = analogRead(sensorPin);
//conversion to string so AS can read it in.
itoa(sensorValue, stringValue, 10);
// Writes value to console for debugging
Serial.println(stringValue);
BTserial.print(stringValue);
BTserial.print(sensorValue);
delay(1000);
source to share
For my entire Android / Arduino project, I use this thread:
(let me know if you need more information, because this method WORKS !!)
Start a Thread connection in your openButton OnClick.
Connection topic (establish a stable connection):
private class ConnectThread extends Thread {
private final BluetoothDevice mmDevice;
private BluetoothSocket mmSocket;
ConnectThread(BluetoothDevice device) {
mmDevice = device;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
//connectedNotification("DIS");
}
mmSocket = tmp;
}
public void run() {
//connectedNotification("Connecting ...");
mBluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect();
beginListenForData();
} catch (IOException connectException) {
try {
mmSocket = (BluetoothSocket) mmDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(mmDevice, 1);
mmSocket.connect();
beginListenForData();
} catch (Exception e2) {
try {
mmSocket.close();
//connectedNotification("DIS");
} catch (IOException closeException) {
//connectedNotification("DIS");
}
}
}
}
void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
//connectedNotification("DIS");
}
}
}
source to share
Hello, maybe what you want is here ... Good luck and hugs from Brazil.
And the author says, “I used to send a buffer from my run method to connectThread, but found myself sometimes getting garbled data at any rate other than a slow baud rate. It turns out that this is because the buffer is overflowing and trying to save up. method is to create a string in the run method from the buffer and then send it to the UI thread through the handler. "Okay
Link below: https://wingoodharry.wordpress.com/2014/04/15/android-sendreceive-data-with-arduino-using-bluetooth-part-2/
same stuff and different url below: http://solderer.tv/data-transfer-between-android-and-arduino-via-bluetooth/
Best wishes sir!
source to share