IOS Core Bluetooth : Writing NSData for Characteristic

后端 未结 5 966
花落未央
花落未央 2021-02-11 01:48

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


        
5条回答
  •  南方客
    南方客 (楼主)
    2021-02-11 02:18

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

提交回复
热议问题