Malek Belkahla Malek Belkahla - 1 month ago 16
iOS Question

IOS Core Bluetooth : Writing NSData for Characteristic

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?

Answer

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

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