I went to a struggle. There are so many tutorials regarding this topic, but I cannot adapt any of those to my project.
What I want to do is simple:
User press the button in Android (Dialog opens, user enters numbeers, presses ok)
Arduino compares data and if it matches send one message to Android, if no - another.
Concept is this.
What I have so far is simple Arduino code
void loop() {
if (Serial.available() > 0) { // if the data came
incomingByte = Serial.read(); // read byte
if(incomingByte == '0') {
digitalWrite(LED, LOW); // if 1, switch LED Off
Serial.println("LED OFF. Press 1 to LED ON!"); // print message
}
if(incomingByte == '1') {
digitalWrite(LED, HIGH); // if 0, switch LED on
Serial.println("LED ON. Press 0 to LED OFF!");
bluetoothSerial.write
}
}
I found great tutorial for sending data from Arduino to Android, but it's made in Thread mode and I cannot adopt it to my AsyncThread solution. This is the main problem :\
My Android AsyncThread code looks like that:
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(ConnectedActivity.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
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)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
Toast.makeText(ConnectedActivity.this, "Connection Failed. Is it a SPP Bluetooth? Try again.", Toast.LENGTH_SHORT).show();
finish();
}
else
{
Toast.makeText(ConnectedActivity.this, "Succeed.", Toast.LENGTH_SHORT).show();
isBtConnected = true;
}
progress.dismiss();
}
}
Solution from the tutorial:
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECIEVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
txtArduino.setText("Data from Arduino: " + sbprint); // update TextView
btnOff.setEnabled(true);
btnOn.setEnabled(true);
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
};
};
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String message) {
Log.d(TAG, "...Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
Full tutorial can be found here:
http://solderer.tv/data-transfer-between-android-and-arduino-via-bluetooth/
I can send data from Android to Arduino with no problem. But receiving it.. nope. Any suggestions?
EDITv2
Silly me. I've put handler and thread's code in my activity. And ran
mConnectedThread = new ConnectedThread();
mConnectedThread.start();
in AsyncTask background task. I can see valid toast message now.
Tnx!
Related
I am doing an app for my arduino sensor I wanted to know how to actually obtain the data from arduino to android studio via bluetooth because in my arduino I put Serial.println("occupied") but when receive in android it somehow mixed with some numbers/bytes like "o2cuppied" or else it will receive seperately in logcat. I don't know what is wrong with it.
Arduino Code:
void setup() {
serial1.begin(9600); //for the bluetooth module
}
void loop() {
//send data to Bluetooth module//
if (dist[0] < dist_threshold) {
serial1.print("Occupied\n");
}
if (dist[1] < dist_threshold) {
serial1.print("Occupied2\n");
}
Android
#Override
protected void onCreate(Bundle savedInstanceState) {
h = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECEIVE_MESSAGE: // if receive massage
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
// and clear
txtArduino.setText("Data from Arduino: " + strIncom);
break;
}
}
};
}
private class ConnectedThread extends Thread {
private final BluetoothSocket bluetoothSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
bluetoothSocket = socket;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
String incomingMessage = new String(buffer, 0, bytes);
Log.d(TAG, "InputStream: " + incomingMessage);
h.obtainMessage(RECEIVE_MESSAGE, bytes, -1, buffer).sendToTarget(); // Send to message queue Handler
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
}
Logcat
2019-11-27 12:28:13.505 12733-12893/com.example.fyp D/MainActivity: InputStream: O
2019-11-27 12:28:13.508 12733-12893/com.example.fyp D/MainActivity: InputStream: ccupied
private StringBuilder sb = new StringBuilder();
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length());
final String finalSbprint = sbprint;
TCP: You have to concatenate the incoming bytes.
But if the Arduino is only going to send text you can make your life easier by letting it send "Occupied\n" instead of "Occupied".
On the receiving side you add a BufferedStreamReader and use its readLine() member to read that line.
I have an Arduino UNO board connected via bluetooth to my Android phone. Everything is OK. Any command from android phone received and executed in Arduino. But the feedback from arduino is buggy.
This is first data from Arduino
device information :
pin 4 set to 0
pin 5 set to 0
pin 6 set to 0
but the second data is come like this
change pin 4 to 1n :
pin 4 set to 0
pin 5 set to 0
pin 6 set to 0
what i expected is
change pin 4 to 1
Here is android code i get from internet
mHandler = new Handler(){
public void handleMessage(android.os.Message msg){
if(msg.what == MESSAGE_READ){
String readMessage = null;
try {
readMessage = new String((byte[]) msg.obj, "UTF-8");
//readMessage[bytes] = '\0';
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
mReadBuffer.append(readMessage+"\n");
}
if(msg.what == CONNECTING_STATUS){
if(msg.arg1 == 1)
mBluetoothStatus.setText("Connected to Device: " + (String)(msg.obj));
else
mBluetoothStatus.setText("Connection Failed");
}
}
};
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = 0;
bytes = mmInStream.available();
if(bytes != 0) {
SystemClock.sleep(100);
bytes = mmInStream.available();
bytes = mmInStream.read(buffer, 0, bytes);
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
public void write(String input) {
byte[] bytes = input.getBytes();
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Show Paired Devices", Toast.LENGTH_SHORT).show();
mReadBuffer.append("Error Sending Data\n");
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
}
}
}
please help.
i dont know how this chould happen, but the rerspond is clear... some one can explain to me, or may be there is better answer??
mHandler = new Handler(){
public void handleMessage(android.os.Message msg){
if(msg.what == MESSAGE_READ){
String readMessage = "";
/*
try {
byte[] readBuf = (byte[]) msg.obj;
readMessage = new String(readBuf, "UTF-8");
readMessage = new String(readBuf, 0,13);
readMessage[bytes] = '\0';
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
*/
readMessage = new String((byte[]) msg.obj, 0, msg.arg1);
mReadBuffer.append(readMessage+"\n");
}
if(msg.what == CONNECTING_STATUS){
if(msg.arg1 == 1)
mBluetoothStatus.setText("Connected to Device: " + (String)(msg.obj));
else
mBluetoothStatus.setText("Connection Failed");
}
}
};
I am building an app which connects through bluetooth but the problem is that it is crushing the device when I try to open the activity as the app should transfer the data from arduino to android app and display on it.I am having problem with the default bluetooth device issue when i see it on terminal
Here is the code
public class BlankActivity extends AppCompatActivity {
Button btnOn, btnOff;
TextView txtString, txtStringLength, sensorView0;
Handler bluetoothIn;
final int handlerState = 0; //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder recDataString = new StringBuilder();
private ConnectedThread mConnectedThread;
// SPP UUID service - this should work for most devices
private static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// String for MAC address
private static String address;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sensors_layout);
//Link the buttons and textViews to respective views
btnOn = (Button) findViewById(R.id.buttonOn);
btnOff = (Button) findViewById(R.id.buttonOff);
txtString = (TextView) findViewById(R.id.txtString);
txtStringLength = (TextView) findViewById(R.id.testView1);
sensorView0 = (TextView) findViewById(R.id.sensorView0);
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) { //if message is what we want
String readMessage = (String) msg.obj; // msg.arg1 = bytes from connect thread
recDataString.append(readMessage); //keep appending to string until ~
int endOfLineIndex = recDataString.indexOf("~"); // determine the end-of-line
if (endOfLineIndex > 0) { // make sure there data before ~
String dataInPrint = recDataString.substring(0, endOfLineIndex); // extract string
//txtString.setText("Data Received = " + dataInPrint);
int dataLength = dataInPrint.length(); //get length of data received
//txtStringLength.setText("String Length = " + String.valueOf(dataLength));
if (recDataString.charAt(0) == '#') //if it starts with # we know it is what we are looking for
{
String sensor0 = recDataString.substring(1, endOfLineIndex); //get sensor value from string between indices 1-5
//String sensor1 = recDataString.substring(6, 10); //same again...
//String sensor2 = recDataString.substring(11, 15);
//String sensor3 = recDataString.substring(16, 20);
sensorView0.setText(" Intensity = " + sensor0 + " Raw "); //update the textviews with sensor values
//sensorView1.setText(" Sensor 1 Voltage = " + sensor1 + "V");
//sensorView2.setText(" Sensor 2 Voltage = " + sensor2 + "V");
//sensorView3.setText(" Sensor 3 Voltage = " + sensor3 + "V");
}
recDataString.delete(0, recDataString.length()); //clear all string data
// strIncom =" ";
dataInPrint = " ";
}
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
// Set up onClick listeners for buttons to send 1 or 0 to turn on/off LED
btnOff.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("0"); // Send "0" via Bluetooth
Toast.makeText(getBaseContext(), "Measurement Off!!!", Toast.LENGTH_SHORT).show();
}
});
btnOn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("1"); // Send "1" via Bluetooth
Toast.makeText(getBaseContext(), "Please Wait ", Toast.LENGTH_SHORT).show();
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(myUUID);
//creates secure outgoing connecetion with BT device using UUID
}
#Override
public void onResume() {
super.onResume();
//Get MAC address from DeviceListActivity via intent
Intent intent = getIntent();
//Get the MAC address from the DeviceListActivty via EXTRA
address = intent.getStringExtra(MainLayout.EXTRA_ADDRESS);
//create device and set the MAC address //I am having problem here in android monitor
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
//I send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
// I have problem with this line
****mConnectedThread.write("x");**
}**
#Override
public void onPause() {
super.onPause();
try {
//Don't leave Bluetooth sockets open when leaving activity
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
}
//Checks that the Android device Bluetooth is available and prompts to be turned on if off
private void checkBTState() {
if (btAdapter == null) {
Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
//create new class for connect thread
private class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
This is the crash code when I am facing when I click the button
at de.zmt.photometerapp.BlankActivity$3.onClick(BlankActivity.java:114)
I have a Raspberry Pi which I am using to read some sensor data and then trying to send that data through Bluetooth RFCOMM socket to Android phone. I can send data from the Android phone to the Raspberry Pi without problems but for some reason I am not able to read the sensor data with the Android phone sent by the Raspberry Pi.
The write function on the Raspberry Pi always returns the right amount of bytes that have been sent and on the Android side I have a thread reading the InputStream and there is a available function to check if there is any bytes to read but it almost every time returns nothing. However, it sometimes reads (maybe 1 time of 20) the sensor data and after the message handler has passed the data back to the another activity and printed the data on a text view, the program crashes.
Maybe someone could give me some explanation why the InputStream isn't receiving any data even though the Raspberry Pi sends the data. Huge thanks in advance!
Here is my BluetoothTransferThread class:
public class BluetoothTransferThread extends Thread {
private final BluetoothSocket connectedSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
private Context context;
private final Handler threadHandler;
public BluetoothTransferThread(BluetoothSocket socket, Context context, Handler mHandler) {
this.context = context;
connectedSocket = socket;
threadHandler = mHandler;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
//Send a transfer thread created message to activity
threadHandler.obtainMessage(BluetoothClientActivity.TRANSFER_THREAD_CREATED).sendToTarget();
int[] buffer;
int readByte;
int i = 0, bytesAvailable;
/**
* Keep listening to the InputStream while connected
*/
while (true) {
try {
//Check if there is bytes available to read in the InputStream
bytesAvailable = mmInStream.available();
if(bytesAvailable > 0) {
buffer = new int[bytesAvailable];
Log.d(getClass().getName(), String.format("value = %d", bytesAvailable));
/*
* Read the stream byte at a time and store it to a buffer until we have received the end of the frame char
*/
do {
//readByte = dInputStream.readUnsignedByte();
readByte = mmInStream.read();
buffer[i] = readByte;
i++;
} while (readByte != 0xEE);
//Send the received data through handler back to activity
threadHandler.obtainMessage(BluetoothClientActivity.MESSAGE_READ, buffer).sendToTarget();
}
try {
currentThread().sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Write to the connected OutStream.
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
Toast.makeText(this.context, "Wrote to the socket", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this.context, "Couldn't write to the socket", Toast.LENGTH_SHORT).show();
}
}
/**
* Close the transfer thread
*/
public void cancel() {
try {
connectedSocket.close();
Toast.makeText(this.context, "Transfer thread socket closed", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(this.context, "Couldn't close the transfer thread socket", Toast.LENGTH_SHORT).show();
}
}
And here is the Raspberry Pi's side code snippet:
case READ_SENSOR_DATA:
/* Serialize the data and send it through the socket */
pthread_mutex_lock(&sensorData->mutex1);
pthread_mutex_lock(&sensorData->mutex5);
serializationLengthPtr = serializeStruct(sendBuffer, sensorData);
pthread_mutex_unlock(&sensorData->mutex1);
pthread_mutex_unlock(&sensorData->mutex5);
sendBuffer[8] = FRAME_END_CHAR;
bytes_sent = write(client, sendBuffer, serializationLengthPtr - sendBuffer + 1);
if(bytes_sent <= 0) {
perror("Write failed!\n");
socketCloseFlag = true;
break;
}
else {
printf("Bytes sent: %d\n", bytes_sent);
}
break;
I receiving 3 data from Arduino and the data just keep coming in. My problem is the data doesn't update to the new received values.
Here is the screenshot from the logcat:
So D/BPM is the value in the textview 68
D/SPo2 is the value in the textview 99
D/temp is the value in textview 28.0
D/read: 71 is for BPM 99 is for SPo2 and 28.11 is for temp.
But the textview values just stuck at 68 99 and 28.0. :(
Here are my code for the Android part:
public class Bluetooth_dataDisplay extends Activity {
//declaration
BluetoothAdapter mAdapter;
private ArrayAdapter adapter;
TextView myLabel;
TextView myLabel1;
TextView myLabel2;
Thread workerThread;
byte[] readBuffer;
int readBufferPosition;
volatile boolean stopWorker;
private ListView listview;
private BluetoothSocket bluetoothSocket;
private ConnectedThread mConnectedThread;
final int handlerState = 0;
private StringBuilder recDataString = new StringBuilder();
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case Constants.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
recDataString.append(readMessage);
Log.d("read",readMessage);
if (recDataString.charAt(0) == '#')
{
String BPM = recDataString.substring(1,3);
String SPO2= recDataString.substring(3,5);
String Temp= recDataString.substring(5,9);
Log.d("BPM", BPM);
Log.d("SPO2", SPO2);
Log.d("Temp", Temp);
myLabel.setText("BPM" + " " + BPM);
myLabel1.setText("SPO2" +" "+ SPO2);
myLabel2.setText("Temp"+" " + Temp);
}
//recDataString.delete(0, recDataString.length());
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth_datadisplay);
myLabel = (TextView)findViewById(R.id.label);
myLabel1 = (TextView)findViewById(R.id.label1);
myLabel2= (TextView)findViewById(R.id.label2);
}//end oncreate
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
//Get MAC address from BluetoothActivity using intent and Extra
String MAC = getIntent().getStringExtra("MAC");
//must declare every time on a new activity if not will result in null error
mAdapter = BluetoothAdapter.getDefaultAdapter();
//create device and set the MAC address
BluetoothDevice bluetoothDevice = mAdapter.getRemoteDevice(MAC);
// Initiate a connection request in a separate thread
ConnectingThread t = new ConnectingThread(bluetoothDevice);
t.start();
}
#Override
public void onPause()
{
super.onPause();
try {
bluetoothSocket.close();
} catch (IOException e) {
Log.e("error", "terminate thread");
e.printStackTrace();
}
}
/**
* Start the ConnectedThread to begin managing a Bluetooth connection
*
* #param socket The BluetoothSocket on which the connection was made
* #param device The BluetoothDevice that has been connected
*/
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();
}
private class ConnectingThread extends Thread {
private final BluetoothSocket bluetoothSocket;
private final BluetoothDevice bluetoothDevice;
public ConnectingThread(BluetoothDevice device) {
BluetoothSocket temp = null;
bluetoothDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
temp = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
bluetoothSocket = temp;
}
public void run() {
// Cancel any discovery as it will slow down the connection
mAdapter.cancelDiscovery();
try {
// This will block until it succeeds in connecting to the device
// through the bluetoothSocket or throws an exception
bluetoothSocket.connect();
} catch (IOException connectException) {
connectException.printStackTrace();
try {
bluetoothSocket.close();
} catch (IOException closeException) {
closeException.printStackTrace();
}
}
// Code to manage the connection in a separate thread
connected(bluetoothSocket, bluetoothDevice);
}
// Cancel an open connection and terminate the thread
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket bluetoothSocket;
private final InputStream mmInputStream;
//private final OutputStream mmOutputStream;
public ConnectedThread(BluetoothSocket socket) {
bluetoothSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
//tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInputStream = tmpIn;
//mmOutputStream = tmpOut;
}//endofConnectedThread(BluetoothSocket socket)
public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInputStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}//end of void run
}//end of connectecthread
}
Because Arduino will be sending in data eg #719928.11 so the index will be in this order (0123456789)
Which is why I did it this way to extract the data:
if (recDataString.charAt(0) == '#')
{
String BPM = recDataString.substring(1,3);
String SPO2= recDataString.substring(3,5);
String Temp= recDataString.substring(5,9);
Log.d("BPM", BPM);
Log.d("SPO2", SPO2);
Log.d("Temp", Temp);
myLabel.setText("BPM" + " " + BPM);
myLabel1.setText("SPO2" +" "+ SPO2);
myLabel2.setText("Temp"+" " + Temp);
}
Just to add more details regarding the data:
BPM and SPO2 are in int (pulse oximeter)
Temp is in float format
So if my pulse oximeter is not on. My data look like this #0028.28 where the first 0 is BPM and the second 0 is SPO2. 28.28 is temp
So if the pulse oximeter is on. My data look like this #669928.28 where 66 is BPM and 99 is SPO2. 28.28 is temp. Below is data displayed in Arduino serial monitor:
Try this
1 .
replace
private StringBuilder recDataString = new StringBuilder();
with this one
private String recDataString = "";
2 . replace
recDataString.append(readMessage);
with this one
recDataString = readMessage ;
Data Parsing for different-2 situations :
if(recDataString.lenth > 0){
//If Oxiometer is OFF
if(recDataString.startsWith(#00) && recDataString.length == 8){
//Do Parsing here #0028.14
String BPM = "0";
String SPO2= "0";
String temp = recDataString.split("00")[1];
myLabel.setText("BPM" + " " + BPM);
myLabel1.setText("SPO2" +" "+ SPO2);
myLabel2.setText("Temp"+" " + Temp);
}
//If Oxiometer is on
if(recDataString.startsWith(#) && recDataString.length() == 10){
//Do Parsing here #779928.08
String BPM = recDataString.substring(1,3);
String SPO2= recDataString.substring(3,5);
String temp = recDataString.substring(5,recDataString.lenth());
myLabel.setText("BPM" + " " + BPM);
myLabel1.setText("SPO2" +" "+ SPO2);
myLabel2.setText("Temp"+" " + Temp);
}
//If String contains # only .
if(recDataString.startsWith(#) && recDataString.length == 1){
//Do nothing or you can decide
}
}
Before recDataString.append(readMessage); try to reset the recDataString first, like this:
recDataString.setLength(0);
Because if it does not reset, it will continue append new strings:
#689928.0
#689928.06899719928.11 ...