IOS Core蓝牙:为特性编写NSData [英] IOS Core Bluetooth : Writing NSData for Characteristic

查看:107
本文介绍了IOS Core蓝牙:为特性编写NSData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码使用IOS Core蓝牙为蓝牙特性(重置设备)写入0xDE值:

I am using the following code to write the 0xDE value for a Bluetooth Caracteristic (Reset Device) using the IOS Core Bluetooth :

...
NSData *bytes = [@"0xDE" dataUsingEncoding:NSUTF8StringEncoding];
[peripheral writeValue:bytes
            forCharacteristic:characteristic
            type:CBCharacteristicWriteWithResponse];
...

我的代码中是否有任何错误,因为该值未正确写入?

is there any mistake in my code because the value is not written properly?

推荐答案

尝试使用单字节值数组创建数据。

Try creating your data with an array of single byte values.

const uint8_t bytes[] = {0xDE};
NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)];

这是创建任意常量数据的有用方法。对于更多字节,

This is a useful approach for creating arbitrary constant data. For more bytes,

const uint8_t bytes[] = {0x01,0x02,0x03,0x04,0x05};
NSData *data = [NSData dataWithBytes:bytes length:sizeof(bytes)];

如果你想创建要使用变量发送的数据,我建议使用NSMutableData并附加字节你需要。它不是很漂亮,但它易于阅读/理解,尤其是当您在嵌入式方面匹配打包结构时。以下示例来自BLE项目,我们正在制作一个简单的通信协议。

If you want to create data to send using variables, I would recommend using NSMutableData and appending the bytes that you need. It isn't very pretty, but it is easy to read / understand, especially when you are matching a packed struct on the embedded side. Example below is from a BLE project where we were making a simple communication protocol.

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];

这篇关于IOS Core蓝牙:为特性编写NSData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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