Swift CoreBluetooth从BLE读取浮点数组 [英] Swift CoreBluetooth Reading a float array from BLE
问题描述
我正在使用CoreBluetooth快速构建iOS应用程序以进行BLE通信.我能够连接并订阅Arduino设备的特征.我能够从该Arduino设备成功读取数据,但它是我现在正在使用Arduino编写的单个浮点值.我知道didUpdateValueFor会将其作为Data对象读取,并且您必须将数据转换为所需的值.我能够将其转换为如下所示的浮点值.我想发送多个浮点值,特别是它们是从加速度计读取的浮点值X YZ.我将它们作为浮点数组发送,但是在应用程序端转换和显示浮点值时遇到了麻烦.任何帮助表示赞赏.谢谢你.
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屋!