读取电池级别Xcode

时间:2014-03-01 20:06:10

标签: iphone core-bluetooth batterylevel

我已经编写了一个应用程序,我试图获取并更新我的cB-OLP425模块上的电池电量。

我使用了以下代码,但有时它给了我70的值,有时它给了我一个值-104。我查看过很多帖子并尝试过很多东西,但似乎没什么用。

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
if([service.UUID isEqual:[CBUUID UUIDWithString:@"180F"]]) {
        for (CBCharacteristic *characteristic in service.characteristics) {
            NSLog(@"discovered service %@", service.UUID);
            if([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"2A19"]]) {
                NSLog(@"Found Notify Characteristic %@", characteristic.UUID);
                 self.mycharacteristic = characteristic;
                [self.testPeripheral readValueForCharacteristic:mycharacteristic];
                [self.testPeripheral setNotifyValue:YES forCharacteristic:mycharacteristic];

               char batlevel;
                [mycharacteristic.value getBytes:& batlevel length:0];

                int n = (float)batlevel;
                int value = n ;

                self.batteryLevel = value;
                NSLog(@"batterylevel1;%f",batteryLevel);
            /* [[NSUserDefaults standardUserDefaults]setFloat: batteryLevel forKey:@"battery_level"];*/
                           }
             } }
 }
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
if([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"2A19"]]) {
                NSLog(@"Found Battery Characteristic %@", characteristic.UUID);
 [mycharacteristic.value getBytes:& batteryLevel length:0];

                return;
 }
 [self.delegate peripheralDidReadChracteristic:mycharacteristic withPeripheral:testPeripheral withError:error];
}

有人可以帮助我!!

1 个答案:

答案 0 :(得分:0)

您的getBytes似乎是个问题。我们使用以下方式阅读应用中的电池电量:

UInt8 batteryLevel = ((UInt8*)value.bytes)[0];

你也可以这样做:

UInt8 batteryLevel;
[value getBytes:&battery length:1];

您需要确保类型为UInt8,否则您会将其读入错误的位置。

另外,请勿在{{1​​}}中立即阅读该值。等到您收到有关该值已更新的通知。文档声明:

  

当您尝试读取特征的值时,外围设备会调用外围设备:didUpdateValueForCharacteristic:error:其委托对象的方法以检索该值。如果成功检索到该值,则可以通过特征的value属性访问它,如下所示: