如果特征中有多个属性,如何读取和写入值?
例如,LED颜色为RGB:
Characteristic: LED彩色UUID: 7A5A0011-D04B-48EB-B3FA-32EB4F0FFAC4 LED颜色和强度的RGB格式。名称绿色名称蓝色格式无符号8位整数访问读取,写入值0- 255格式无符号8位整数访问读取,写入值0- 255名称红色格式无符号8位整数访问读取,写入值0- 255
那么如何读取/写入RGB的值呢?使用下面的代码,我只得到一个值
if ([service.UUID isEqual:[CBUUID UUIDWithString:LED_Service_UUID]]){
for (CBCharacteristic *aChar in service.characteristics) {
/********* Characteristic: LED Link***************/
NSLog(@"%@",aChar.UUID);
if ([aChar.UUID isEqual:[CBUUID UUIDWithString: LED_CHAR_COLOR_UUID]]) {
[peripheral readValueForCharacteristic:aChar];
NSLog(@"%@%@%@",aChar.value,aChar.value,aChar.value);
}发布于 2015-05-22 11:47:44
if ([aChar.UUID isEqual:[CBUUID UUIDWithString: LED_CHAR_COLOR_UUID]])
{
_colorCharacteristic = aChar; //It's a property, save it
[peripheral readValueForCharacteristic:aChar];
}这应该触发委托方法:peripheral:didUpdateValueForCharacteristic:error:。
在里面,它:
if ([characteristic UUID] isEqual:[CBUUID UUIDWithString: LED_CHAR_COLOR_UUID]])
{
NSData *valueData = [characteristic value];
}对于每个组成部分(红色、绿色、蓝色、强度):
int aComponent;
NSData *aComponentData = [valueData subdataWithRange:NSMakeRange(0, 2)]; //Range to be defined for each components
[aComponentData getBytes:&aComponent length:sizeof(aComponent)];
NSLog(@"aComponent: %d", aComponent);然后可以使用UIColor从每个组件创建一个colorWithRed:green:blue:alpha:。
要编写,您必须再次拥有一个看起来尊重所使用的格式的NSData。
uint8_t colorValues [] = {redValue, greenValue, blueValue, intensityValue};
NSData *data = [NSData dataWithBytes:colorValues length:sizeof(colorValues)];
[_peripheral writeValue:yourValueData forCharacteristic:_colorCharacteristic type: CBCharacteristicWriteWithResponse];` //(or `CBCharacteristicWriteWithoutResponse` depending on the doc of your device).https://stackoverflow.com/questions/30367781
复制相似问题