繁体   English   中英

BLE(蓝牙启用设备)iOS

[英]BLE(BlueTooth Enable device) ios

如果特性中有多个属性,如何读写值?

例如,LED颜色为RGB:

特征: 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);
       }
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);

然后,您可以使用colorWithRed:green:blue:alpha:从每个组件创建一个UIColor

要编写,您必须再次拥有一个看起来尊重所使用格式的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).

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM