iOS Swift 3 BLE CBCharacteristic / Size 8 Bytes (4 Words) / How to separate the words

Question

I want to read out data from a Bluetooth Module. There is a characteristic with 4 values, stored in 8 bytes/4 words.

Here is the data, that is stored in characteristic.value:

0x01 0x01 0x00 0x01 0x04 0x05 0x00 0x01

I work with Swift 3.

Here´s the code

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {

 let data = characteristic.value
 let dataString = String(data: data!, encoding: String.Encoding.utf8)
 print("Data: \(String(describing: dataString))")
}

The "print" function shows the following result in the output Window:

datastring: Optional("\u{01}\u{01}\0\u{01}\u{04}\u{05}\0\u{01}")

I stuck in separating the CBCharacteristic content (8 Bytes shown above) into 4 separate values (each value should consist of 1 word).

I´d like to have that result:

Value 1: 0x01 0x01
Value 2: 0x00 0x01
Value 3: 0x04 0x05
Value 4: 0x00 0x01

Each 2 Bytes should be one value. Could you please help me to separate those value and to convert that words into integers?

Thank you very much.

Very best regards Bursche


Show source
| ios   | xcode   | swift   | bluetooth   | bluetooth-lowenergy   2017-09-05 23:09 1 Answers

Answers to iOS Swift 3 BLE CBCharacteristic / Size 8 Bytes (4 Words) / How to separate the words ( 1 )

  1. 2017-09-06 12:09

    Try this code for get integer value from 2 bytes. LSB(little endian)

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    
       let value = [UInt8](characteristic.value!)
       let newValue = ((Int16(value[1]) << 8) | (Int16(value[0])))
       let intValue = Int(newValue)
       print(intValue)
    }
    

Leave a reply to - iOS Swift 3 BLE CBCharacteristic / Size 8 Bytes (4 Words) / How to separate the words

◀ Go back