user1114881
user1114881

Reputation: 751

reading battery level ble Xcode

I have written an app which I am trying to get and update the battery level on my cB-OLP425 module.

I have used the following code but sometimes it gives me a value of 70 and at other times it gives me a value of -104. I have looked at numerous posts and tried a lot of things but nothing seems to work.

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

Could someone please help me!!

Upvotes: 1

Views: 4493

Answers (1)

christophercotton
christophercotton

Reputation: 5859

Your getBytes seems to be the issue. We read the battery level in our app using:

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

You could also do it with:

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

You need to make sure the type is UInt8 otherwise you would read it into the wrong location.

Also, don't read the value right away in the didDiscoverCharacteristicsForService. Wait until you get notified that the value has been updated. The docs state:

When you attempt to read the value of a characteristic, the peripheral calls the peripheral:didUpdateValueForCharacteristic:error: method of its delegate object to retrieve the value. If the value is successfully retrieved, you can access it through the characteristic’s value property, like this:

Upvotes: 1

Related Questions