Search code examples
c#uwpiotbtle

C# Converting a byte array from BT LE device


I am using a Nordic Thingy:52 to record environmental data in a UWP app and have followed the example in the Windows Universal Sample apps to connect to BT LE devices.

So far I have been able to connect to the device to retrieve service and characteristic information but when receiving the actual data from the sensors I can't manage to convert the byte array into usable data.

async void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
    // An Indicate or Notify reported that the value has changed.
    var reader = DataReader.FromBuffer(args.CharacteristicValue);
    byte[] input = new byte[reader.UnconsumedBufferLength];
    reader.ReadBytes(input);
}

When checking the contents of the byte array you can see that something has been received but I'm stuck when it comes to knowing how to convert this array to useful data.

Code to read the byte array

Data specification for data sent by the device


Solution

  • From the document we can see the definition of pressure data:

    enter image description here

    5 bytes contains one int32 for integer part and one uint8 for decimal part. Uint is hPa.

    You get a string like this:

            Int32 pressureInteger = BitConverter.ToInt32(input, 0); //252-3-0-0
            string pressureString = pressureInteger.ToString() + "." + input[4].ToString() + "hPa";
    

    The string will be "1020.28hPa"

    More reference "BitConverter Class" and note little-endian/big-endian.