Mal*_*hla 3 ios core-bluetooth
我使用以下代码使用IOS Core蓝牙为蓝牙特性(重置设备)写入0xDE值:
...
NSData *bytes = [@"0xDE" dataUsingEncoding:NSUTF8StringEncoding];
[peripheral writeValue:bytes
forCharacteristic:characteristic
type:CBCharacteristicWriteWithResponse];
...
Run Code Online (Sandbox Code Playgroud)
我的代码中是否有任何错误,因为该值未正确写入?
小智 6
尝试使用单字节值数组创建数据.
const uint8_t bytes[] = {0xDE};
NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)];
Run Code Online (Sandbox Code Playgroud)
这是创建任意常量数据的有用方法.对于更多字节,
const uint8_t bytes[] = {0x01,0x02,0x03,0x04,0x05};
NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)];
Run Code Online (Sandbox Code Playgroud)
如果要创建要使用变量发送的数据,我建议使用NSMutableData并附加所需的字节.它不是很漂亮,但它易于阅读/理解,尤其是当您在嵌入式端匹配打包结构时.以下示例来自BLE项目,我们正在制作一个简单的通信协议.
NSMutableData *data = [[NSMutableData alloc] init];
//pull out each of the fields in order to correctly
//serialize into a correctly ordered byte stream
const uint8_t start = PKT_START_BYTE;
const uint8_t bitfield = (uint8_t)self.bitfield;
const uint8_t frame = (uint8_t)self.frameNumber;
const uint8_t size = (uint8_t)self.size;
//append the individual bytes to the data chunk
[data appendBytes:&start length:1];
[data appendBytes:&bitfield length:1];
[data appendBytes:&frame length:1];
[data appendBytes:&size length:1];
Run Code Online (Sandbox Code Playgroud)
Swift 3.0:如果有人想知道 Swift 的格式略有不同,因为 writeValue 可以从数组中获取计数。
let value: UInt8 = 0xDE
let data = Data(bytes: [value])
peripheral.writeValue(data, for: characteristic, type: .withResponse)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5589 次 |
| 最近记录: |