Javier Romero.
Javier Romero.

Reputation: 95

Data sent from Android to HC-05 Bluetooth Arduino not showing

I am creating an Android app that allows me to control a device connected to Arduino using Bluetooth, with Android 4.4.2, Arduino Uno and HC-05 Module.

Right now I'm finding serious difficulties to print data in the Arduino serial (in order to verify if it's really working). I tried everything I have found in this or other forums related to this topic.

For the moment, I have been able to detect the devices, pair with them and create the Socket and the OutputStream, but for some reason the data doesn't show up.

The code is 2 basic Activities and their layouts (Android) and the Arduino code:

Image of how it shows the available devices.

Image of how now that device is paired with our Android Device.

GetPaired.java:

Basically gets the available devices, show them in a custom ListView, allows you to pair/unpair with them and after you get the device paired, you go to the ConnectionControl activity.

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

    public class GetPaired extends Activity {

    ListView listViewPaired;
    ListView listViewDetected;
    ArrayList<String> arrayListpaired;
    Button buttonSearch,buttonControl;
    ArrayAdapter<String> adapter, detectedAdapter;
    BluetoothDevice bdDevice;
    ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
    ListItemClickedonPaired listItemClickedonPaired;
    BluetoothAdapter bluetoothAdapter = null;
    ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
    ListItemClicked listItemClicked;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth_demo);
        listViewDetected = (ListView) 
        findViewById(R.id.listViewDetected);
        listViewPaired = (ListView) findViewById(R.id.listViewPaired);
        buttonSearch = (Button) findViewById(R.id.buttonSearch);
        buttonControl = (Button) findViewById(R.id.buttonControl);
        arrayListpaired = new ArrayList<String>();
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice();
        listItemClickedonPaired = new ListItemClickedonPaired();
        arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
        adapter = new ArrayAdapter<String>(GetPaired.this, 
    R.layout.custom_layout, arrayListpaired);
        detectedAdapter = new ArrayAdapter<String>(GetPaired.this, 
    R.layout.custom_layout);
        listViewDetected.setAdapter(detectedAdapter);
        listItemClicked = new ListItemClicked();
        detectedAdapter.notifyDataSetChanged();
        listViewPaired.setAdapter(adapter);
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        //Get all the paired bluetooth devices with Android.
        getPairedDevices();
        listViewDetected.setOnItemClickListener(listItemClicked);
        listViewPaired.setOnItemClickListener(listItemClickedonPaired);
    }

    private void getPairedDevices() {
        Set<BluetoothDevice> pairedDevice = 
    bluetoothAdapter.getBondedDevices();
        if (pairedDevice.size() > 0) {
            for (BluetoothDevice device : pairedDevice) {
                arrayListpaired.add(device.getName() + "\n" + 
    device.getAddress());
                arrayListPairedBluetoothDevices.add(device);
                break;
            }
        }
        adapter.notifyDataSetChanged();
    }

    //When clicked a bluetooth device from the available list, a bond is 
    created between them.
    class ListItemClicked implements OnItemClickListener{
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int 
    position, long id) {
            // TODO Auto-generated method stub
            bdDevice = arrayListBluetoothDevices.get(position);
            Log.i("Log", "The device : " + bdDevice.toString());
            Boolean isBonded = false;
            try {
                isBonded = createBond(bdDevice);
                if (isBonded) {
                    getPairedDevices();
                    adapter.notifyDataSetChanged();
                    Log.i("Log", "The bond is created: " + isBonded);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            connect(bdDevice);
        }

    }
    //When clicked in the list of paired devices, you remove the bond and 
    the pairing.
    class ListItemClickedonPaired implements OnItemClickListener{
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int 
    position, long id) {
            bdDevice = arrayListPairedBluetoothDevices.get(position);
            try {
                Boolean removeBonding = removeBond(bdDevice);
                if (removeBonding) {
                    arrayListpaired.remove(position);
                    adapter.notifyDataSetChanged();
                }
                Log.i("Log", "Removed" + removeBonding);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private Boolean connect(BluetoothDevice bdDevice) {
        Boolean bool = false;
        try {
            Log.i("Log", "service method is called ");
            Class cl = Class.forName("android.bluetooth.BluetoothDevice");
            Class[] par = {};
            Method method = cl.getMethod("createBond", par);
            bool = (Boolean) method.invoke(bdDevice);
        } catch (Exception e) {
            Log.i("Log", "Inside catch of serviceFromDevice Method");
            e.printStackTrace();
        }
        return bool.booleanValue();
    }


    public boolean removeBond(BluetoothDevice btDevice)
            throws Exception {
        Class btClass = 
    Class.forName("android.bluetooth.BluetoothDevice");
        Method removeBondMethod = btClass.getMethod("removeBond");
        Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
        return returnValue.booleanValue();
    }


     public boolean createBond(BluetoothDevice btDevice)
            throws Exception {
        Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
        Method createBondMethod = class1.getMethod("createBond");
        Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
        return returnValue.booleanValue();
     }


     //Searches for available bluetooth devices to add them to the 
     Detected 
     List.
     private BroadcastReceiver myReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                Toast.makeText(context, "ACTION_FOUND", 
     Toast.LENGTH_SHORT).show();

                BluetoothDevice device = 
     intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (arrayListBluetoothDevices.size() < 1) // this checks 
     if the size of bluetooth device is 0,then add the
                {                                           // device to 
     the arraylist.
                    detectedAdapter.add(device.getName() + "\n" + 
     device.getAddress());
                    arrayListBluetoothDevices.add(device);
                    detectedAdapter.notifyDataSetChanged();
                } else {
                    boolean flag = true;    // flag to indicate that 
     particular device is already in the arlist or not
                    for (byte i = 0; i < arrayListBluetoothDevices.size(); 
     i++) {
                        if  
(device.getAddress().equals(arrayListBluetoothDevices.get(i).getAddress())
    ) {
                            flag = false;
                        }
                    }
                    if (flag == true) {
                        detectedAdapter.add(device.getName() + "\n" + 
     device.getAddress());
                        arrayListBluetoothDevices.add(device);
                        detectedAdapter.notifyDataSetChanged();
                    }
                }
            }
        }
     };

     //Method that starts the search of bluetooth devices to connect with.
     public void startSearching(View v) {
        arrayListBluetoothDevices.clear();
        Log.i("Log", "in the start searching method");
        IntentFilter intentFilter = new 
    IntentFilter(BluetoothDevice.ACTION_FOUND);
        GetPaired.this.registerReceiver(myReceiver, intentFilter);
        bluetoothAdapter.startDiscovery();
     }


     //When you have the device paired with Android, you can go to the 
     next 
     Activity, where the proper connection is stablished.
     public void onControl(View v) {
        if (arrayListPairedBluetoothDevices.size() > 0) {
            Log.i("Log", "There is a paired device.");
            Intent sipoptent = new Intent(getApplicationContext(), 
     ConnectionControl.class).putExtra("Bluetooth", 
     arrayListPairedBluetoothDevices.get(0));
            startActivity(sipoptent);
            if (arrayListPairedBluetoothDevices.get(0) != null) {
            } else {
            }
        } else {
            Log.i("Log", "Not paired to a device yet.");
                Toast.makeText(GetPaired.this, "Not paired to a device 
     yet.", 
     Toast.LENGTH_SHORT).show();

            }
        }
     }

The ConnectionControl Activity:

Receives an intent with a BluetoothDevice Object, as the device we are going to connect with. Creates the BluetoothSocket, the connection Thread the OutputStream.

*In this part of the code I tried to get another UUID, but again couldn't find anything.

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.util.UUID;
import java.io.OutputStream;

public class ConnectionControl extends AppCompatActivity {
Button on, off;
private BluetoothSocket btSocket = null;
private BluetoothDevice device;
private OutputStream mmOutStream =null;
// SPP UUID service - this should work for most devices
private static final UUID BTMODULEUUID = UUID.fromString("00001101-
0000-1000-8000-00805F9B34FB");

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
on = (Button) findViewById(R.id.onbutton);
off = (Button) findViewById(R.id.offbutton);
device = getIntent().getExtras().getParcelable("Bluetooth"); 
//Bluetooth device information retrieved by an Intent.
Toast.makeText(ConnectionControl.this, device.getAddress(), 
Toast.LENGTH_SHORT).show();
}

@Override
public void onResume() {
    super.onResume();
    try {
        //Creation of the socket of the connection.
        btSocket = createBluetoothSocket(device);
    } catch (IOException e) {
        Toast.makeText(getBaseContext(),"Socket connection failed.", 
Toast.LENGTH_LONG).show();
    }
    // Establish the Bluetooth socket connection.
    try {
        btSocket.connect();
        ConnectedThread(btSocket);
        write("x");
    } catch (IOException e) {
        try {
            btSocket.close();
        } catch (IOException e2) {}
    }
}

//Creates secure outgoing connecetion with BT device using UUID
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) 
throws IOException {
    return  device.createRfcommSocketToServiceRecord(BTMODULEUUID);
}

//Creates the OutputStream from the socket.
public void ConnectedThread(BluetoothSocket socket) {
    OutputStream tmpOut = null;
    try {
        tmpOut = socket.getOutputStream();
    } catch (IOException e) {
        Toast.makeText(getBaseContext(), "Connection Not 
Established.", Toast.LENGTH_LONG).show();
    }
    Toast.makeText(getBaseContext(), "Connection Established.",   Toast.LENGTH_LONG).show();
    mmOutStream = tmpOut;
}

@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
    }
}

    //Transforms a String input into an array of bytes to send to the bluetooth device.
    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(), "Conection failed.", Toast.LENGTH_LONG).show();
        }
    }

public void onON(View view){
    write("0");
}
public void onOFF(View view){
    write("1");
}
}

And the Arduino code:

In the Arduino hardware I connected the 5V and already entered in AT mode to the Bluetooth to change its name before.

    #include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

What can I try next?

Upvotes: 0

Views: 2415

Answers (1)

Javier Romero.
Javier Romero.

Reputation: 95

UPDATE:

If you have to use this code for a project feel free to use it.

I have managed to solve the issue, the Arduino code was the problem, this is the working code:

#include <SoftwareSerial.h>
SoftwareSerial BTserial(11, 10); // RX | TX
char c = ' ';
void setup() 
{
Serial.begin(9600);
Serial.println("Arduino is ready");

// HC-05 default serial speed for commincation mode is 9600
BTserial.begin(9600);  
}

void loop()
{
if (BTserial.available())
{  
    c = BTserial.read();
    Serial.write(c);
}

// Keep reading from Arduino Serial Monitor and send to HC-05
if (Serial.available())
{
    c =  Serial.read();
    BTserial.write(c);  
}

}

Upvotes: 1

Related Questions