Swift CoreBluetooth 从 BLE 读取浮点数组 [英] Swift CoreBluetooth Reading a float array from BLE

查看:18
本文介绍了Swift CoreBluetooth 从 BLE 读取浮点数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)

推荐答案

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

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)")

这篇关于Swift CoreBluetooth 从 BLE 读取浮点数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆