I am building an iOS application in swift using CoreBluetooth for BLE communication. I am able to connect, and subscribe to characteristics of an Arduino device. I am able to read data from that Arduino device successfully but it is a single float value I am writing with the Arduino right now. I know didUpdateValueFor reads it in as a Data object and you have to convert the data into the values you are looking for. I was able to convert it into a float value as displayed below. I want to send multiple float values, specifically they are readings from the accelerometer, float values X Y Z. I am sending them as a float array but I am having trouble converting and displaying the float values on the application side. Any help is appreciated. Thank You.
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
guard characteristic == rxCharacteristic,
let data:Data = characteristic.value
else { return }
let number: Float = data.withUnsafeBytes {
(pointer: UnsafePointer<Float>) -> Float in
return pointer.pointee
}
print("\nValue Received : ", number)
Edit: this is the code I used for testing getting an array of floats from Data representation :
let arr: [Float] = [32.0, 4.0, 1.2]
let data = Data(buffer: UnsafeBufferPointer(start: arr, count: arr.count))
print("---> data: \(data)")
var myFloatArray = Array<Float>(repeating: 0, count: data.count/MemoryLayout<Float>.stride)
myFloatArray.withUnsafeMutableBytes { data.copyBytes(to: $0) }
print("---> myFloatArray: \(myFloatArray)")