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进制形式,然后根据蓝牙通讯协议,获取到对应的数据