iOS蓝牙4.0开发基本使用

1.创建中心角色

CBCentralManager *m_centralManager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];

2.扫描外部设备

NSArray services = [NSArray arrayWithObjects:[CBUUID UUIDWithString:@"FFF0"], nil];//FFF0:用来搜索的UUID [m_centralManager scanForPeripheralsWithServices:services options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES }]; //2.1扫描外部设备前先检查手机蓝牙是否开启 - (void)centralManagerDidUpdateState:(CBCentralManager )central //三种状态1.CBCentralManagerStateUnsupported设备不支持蓝牙4.0 2.CBPeripheralManagerStatePoweredOn蓝牙打开 3.CBPeripheralManagerStatePoweredOff蓝牙未打开

3.扫描成功后停止扫描

[m_centralManager stopScan]

4.连接外部设备

[CBCentralManager connectPeripheral:[BLEManager shareBLEManager].m_peripheral options:nil];//必须是扫描到了设备才去连接外设,且每次都要记得清空扫描的设备,做到每次连接前都去扫描,扫描到硬件,然后去连接

5.扫描外设的服务和特征

for ( CBService service in peripheral.services )//遍历外设所有的服务 if ([service.UUID isEqual:[CBUUID UUIDWithString:sUUID]]) {//匹配找到服务UUID for ( CBCharacteristic characteristic in service.characteristics ) {//遍历服务对应的所有特征 if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:cUUID]]) {//找到写入指令的UUID [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];//写入指令

6.发现蓝牙服务代理方法

-(void)peripheral:(CBPeripheral )peripheral didDiscoverServices:(NSError )error

7.发现蓝牙特征的代理方法

(void)peripheral:(CBPeripheral )peripheral didDiscoverCharacteristicsForService:(CBService )service error:(NSError *)error

8.蓝牙发送成功或者失败代理方法

-(void)peripheral:(CBPeripheral )peripheral didWriteValueForCharacteristic:(CBCharacteristic )characteristic error:(NSError *)error

9.蓝牙连接成功代理方法

-(void)centralManager:(CBCentralManager )central didConnectPeripheral:(CBPeripheral )peripheral//一般硬件都需要每隔1秒或者3秒发送一条指令,具体要看蓝牙协议

10.蓝牙连接失败代理方法

-(void)centralManager:(CBCentralManager )central didDisconnectPeripheral:(CBPeripheral )peripheral error:(NSError *)error

11.蓝牙写入指令后返回数据代理方法

-(void)peripheral:(CBPeripheral )peripheral didUpdateValueForCharacteristic:(CBCharacteristic )characteristic error:(NSError )error //匹配到接受通知的UUID来获取返回的数据 if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"fff3"]]) {//FFF3是定义接受通知的UUID Byte characByte = (Byte *)[characteristic.value bytes];//获取到返回的数据,16进制形式,然后根据蓝牙通讯协议,获取到对应的数据

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 首先进一则广告: 蓝牙技术联盟(Bluetooth SIG)2010年7月7日宣布,正式采纳蓝牙4.0核心规范(B...
    L泽阅读 1,473评论 3 4
  • 本文主要以蓝牙4.0做介绍,因为现在iOS能用的蓝牙也就是只仅仅4.0的设备 用的库就是core bluetoot...
    暮雨飞烟阅读 861评论 0 2
  • 遇到一个对的人 就是 你会感到世界的暖意吧 即使痛苦着 想起你 也会不动声色的微笑起来
    散阳阅读 346评论 0 0
  • 10月16日14:55,蔡康永发微博告别《康熙》,随后小S也立马发微博表示将和康永共同进退。我看到微博的时候是58...
    小九九九诶阅读 1,819评论 11 21
  • 顺其自然 人生最随性的是一切顺其自然,每个人都希望任何事物都顺其自然,自然资源是最好不过的,因为它本真,一切自...
    蕙蕙儿阅读 177评论 0 0