当前位置: 首页 > 工具软件 > CoreBlueTooth > 使用案例 >

ios corebluetooth蓝牙4.0事例

颜畅
2023-12-01

转载:http://www.cocoachina.com/bbs/read.php?tid=162212

蓝牙4.0 不需要配对。

每个device 有UUID来标识。
CBCentralManager 蓝牙管理
CBPeripheral 蓝牙外设 CFUUIDRef 标识
CBService CBUUID 标识
CBCharacteristic 特征(例如蓝牙里面点亮led、打开蜂鸣等) CBUUID 标识
// scaning........
- (IBAction)scanBle:(id)sender {
UIButton *btn = (UIButton *)sender;
[_centralManager scanForPeripheralsWithServices:nil options:0];
[btn setTitle:@"scaning..." forState:UIControlStateNormal];
}
// 选取符合的蓝牙
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
// if (RSSI.integerValue > -15) {
// NSLog(@"信号太强,好像不对");
// return;
// }
// if (RSSI.integerValue < -35) {
// NSLog(@"信号太弱了,离近点再试");
// return;
// }
if (self.discoveredPeripheral != peripheral
&& [[self UUIDToString:peripheral.UUID] isEqualToString:TRANSFER_PERIPHERAL_UUID]) {
self.discoveredPeripheral = peripheral;
self.discoveredPeripheral.delegate = self;
[_btnScan setTitle:peripheral.name forState:UIControlStateNormal];
}
}
// connect the ble
- (IBAction)connectTheBle:(id)sender {
UIButton *btn = (UIButton *)sender;
[btn setTitle:@"connecting" forState:UIControlStateNormal];
[self.centralManager connectPeripheral:self.discoveredPeripheral options:nil];
}
// 蜂鸣指令
- (IBAction)btnSoundPressed:(id)sender {
Byte buzVal = 0x04;
NSData *data = [[NSData alloc] initWithBytes:&buzVal length:1];
CBCharacteristic *characteristic = nil;
for (CBService *service in self.discoveredPeripheral.services) {
NSLog(@"--------service = %s ------nn",[self CBUUIDToString:service.UUID]);
const char *CServieUUID = [self CBUUIDToString:service.UUID];
const char *CSoundUUID = [TRANSFER_SERVICE_SOUND_UUID cStringUsingEncoding:NSASCIIStringEncoding];
int n = strcmp(CServieUUID, CSoundUUID);
if (n == 0) {
for (CBCharacteristic *cha in service.characteristics) {
NSLog(@"--------characteristic = %s ------nn",[self CBUUIDToString:cha.UUID]);
if (strcmp(,) == 0) {
characteristic = cha;
break;
}
}
break;
}
}
[self.discoveredPeripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithoutResponse];
}
以上为蓝牙4.0 外设和 iphone的交互。

 类似资料: