[英]reading battery level ble Xcode
我编写了一个应用,试图获取和更新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];
}
有人可以帮我!
您的getBytes
似乎是问题所在。 我们使用以下方法在应用程序中读取电池电量:
UInt8 batteryLevel = ((UInt8*)value.bytes)[0];
您还可以使用以下方法进行操作:
UInt8 batteryLevel;
[value getBytes:&battery length:1];
您需要确保类型为UInt8
否则将其读入错误的位置。
另外,不要立即在didDiscoverCharacteristicsForService
读取值。 等待,直到您收到该值已更新的通知。 文档状态:
当您尝试读取特征值时,外围设备调用其委托对象的外围设备:didUpdateValueForCharacteristic:error:方法来检索该值。 如果成功检索到值,则可以通过特征的value属性访问它,如下所示:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.