Read characteristic value using Android BLE

stellarhawk 34 picture stellarhawk 34 · Mar 24, 2018 · Viewed 9.3k times · Source

I am relatively new to BLE, android development and java. I am trying to send 20 pieces of data from a microcontroller, via BLE, to my android phone. Using the nRF connect application, I know that the services and values are being created correctly from the microcontroller.

To read them on the android application, I am using the template BluetoothLeGatt application provided in Android Studio. It shows me the services and characteristics (for some reason it shows more services than I have actually created), however only one service shows me a value that is not NULL in the end. I have encoded the value 0x22 in my microcontroller, and the Android Log says gives me the following

03-24 17:13:29.498 23696-23696/com.example.android.bluetoothlegatt D/BLE_VALUE_READ: [B@b95cc24

instead of 0x22. This is using the function

Log.d("BLE_VALUE_READ", String.valueOf(characteristic.getValue()));

I have placed the command inside this function of the template application.

public void readCharacteristic(BluetoothGattCharacteristic characteristic) {
    if (mBluetoothAdapter == null || mBluetoothGatt == null) {
        Log.w(TAG, "BluetoothAdapter not initialized");
        return;
    }
    mBluetoothGatt.readCharacteristic(characteristic);
    Log.d("CharacteristicRead", String.valueOf(characteristic)); // try to get characteristic uuid?
    Log.d("BLE_VALUE_READ", String.valueOf(characteristic.getValue())); // Try to read value
}

How can I get to the actual value of that is in the service/characteristic, which is 0x22? I want to read 20 values in total and then store them in an array as float values in order to ultimately use them for image reconstruction.

Any help would be very much appreciated.

Thank you!

Answer

Emil picture Emil · Mar 24, 2018

characteristic.getValue() returns a byte array. You need to transform the bytes into the desired format.

But after you have called readCharacteristic, you need to wait for the onCharacteristicRead callback before you can extract the value.