Swift CoreBluetooth 从 BLE 读取浮点数组

Swift CoreBluetooth Reading a float array from BLE

我正在 swift 中构建一个 iOS 应用程序,使用 CoreBluetooth 进行 BLE 通信。我能够连接并订阅 Arduino 设备的特性。我能够成功地从该 Arduino 设备读取数据,但它是我现在正在用 Arduino 写入的单个浮点值。我知道 didUpdateValueFor 将它作为数据对象读取,您必须将数据转换为您要查找的值。我能够将其转换为浮点值,如下所示。我想发送多个浮点值,特别是它们是加速度计的读数,浮点值 X Y Z。我将它们作为浮点数组发送,但在应用程序端转换和显示浮点值时遇到问题。任何帮助表示赞赏。谢谢你。

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)

编辑:这是我用于测试从数据表示中获取浮点数组的代码:

    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: [=10=]) }

    print("---> myFloatArray: \(myFloatArray)")