Chitrang
Chitrang

Reputation: 5097

How to write byte array with BluetoothGattCharacteristic in BLE?

This code is working and LED is also turning off.

                byte cmd[] = {(byte) 0xff};
                mWrChar.setValue(cmd);
                mBleGatt.writeCharacteristic(mWrChar);

But I want to pass "0x0801000" as byte array in BluetoothGattCharacteristic, how to do this?

Similar nRF Connect application.

enter image description here

Upvotes: 1

Views: 4841

Answers (2)

gbossa
gbossa

Reputation: 529

This is the method I use to format a hex data, like yours 0x08010000, as a byte array. Then you can write it to characteristics.

public static byte[] hexToByteData(String hex)
{
    byte[] convertedByteArray = new byte[hex.length()/2];
    int count  = 0;

    for( int i = 0; i < hex.length() -1; i += 2 )
    {
        String output;
        output = hex.substring(i, (i + 2));
        int decimal = (int)(Integer.parseInt(output, 16));
        convertedByteArray[count] =  (byte)(decimal & 0xFF);
        count ++;
    }
    return convertedByteArray;
}

Hope it helps.

Upvotes: 1

Thern
Thern

Reputation: 1059

You can just pass an array to the variable cmd. But you need to know if the byte array is MSO (most significant octet) -> LSO (least significant octet) or LSO -> MSO. Typically, characteristics use LSO -> MSO, which means that the first octet in your byte array is the least significant octet.

In the concrete case, note that your characteristic is composed of four bytes: 0x08|01|00|00

Then you have:

MSO -> LSO: 0x08|01|00|00 -> {0x08, 0x01, 0x00, 0x00}

LSO -> MSO: 0x08|01|00|00 -> {0x00, 0x00, 0x01, 0x08}

Check out which one is relevant in your case, or try out both and see what happens. Your code will then be something like this (I assume LSO -> MSO):

byte[] cmd = {0x00, 0x00, 0x01, 0x08};
mWrChar.setValue(cmd);
mBleGatt.writeCharacteristic(mWrChar);

Upvotes: 2

Related Questions