Read characteristic value using Android BLE
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.
![stellarhawk 34](https://lh6.googleusercontent.com/-TiNzHzxbVdQ/AAAAAAAAAAI/AAAAAAAAABE/9GwNCtv0iOU/photo.jpg?sz=256)
stellarhawk 34
Updated on June 18, 2022Comments
-
stellarhawk 34 about 2 years
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!
-
stellarhawk 34 over 6 yearsThanks! But why exactly does the getValue() function return a byte array if BLE operations are single bytes?
-
Emil over 6 yearsWhere did you get the info that "BLE operations are single bytes"? All GATT operations that include characteristic values are operated on byte arrays.
-
Amanpal Singh about 6 yearssome times onCharacteristicRead doesn't call. so for that what should i do?
-
Emil about 6 yearsAsk a new question and add all your details.
-
Farruh Habibullaev almost 5 yearsWhat a brilliant clue. I have been struggling with this for a week until I found this little information. Thank you. It helped me a lot.
-
Arbaz.in over 2 yearsbut every time i am getting null value