Android Bluetooth Application

Viewed 272

Hi I'm sort of new to developing on android and have recently started working with the bluetooth API. I've been able to connect my phone to HC-06 hooked up to my Arduino NANO. However I cannot seem to transfer data correctly. My goal is to grab the current value from the device and save it to a variable on the app while also displaying it. Here is my code for both the arduino and the 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();
    }

}

Arduino

#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);  
2 Answers

Hello there maybe what u want are here...Good luck and big hugs from Brasil.

And the author say this " I used to send the buffer from my run method in the connectThread but found that I would sometimes get garbled data with anything but slow data rates. It turns out this was because the buffer was getting full and struggling to keep up. A much better method is to create a string in the run method from the buffer and then send that to the UI thread via the handler.". ok

The link bellow : https://wingoodharry.wordpress.com/2014/04/15/android-sendreceive-data-with-arduino-using-bluetooth-part-2/

same stuff and another url bellow : http://solderer.tv/data-transfer-between-android-and-arduino-via-bluetooth/

Best regards, sir !!

Related