ios corebluetooth蓝牙4.0事例

转载: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的交互。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值