(一)CoreBluetooth iOS 蓝牙 “中心模式”

ゞ 浴缸里的玫瑰 2022-06-14 04:43 272阅读 0赞

使用Corebluetooth框架进行蓝牙开发,有两种模式:一种是中心模式,另一种是外设模式。
中心模式
分为以下几步:
1.建立中心设备 2.扫描外部设备 3.连接外部设备 4.扫描外部设备的服务和特征 5.利用外部设备的特征与外部设备手法数据

一、首先导入框架 CoreBluetooth/CoreBluetooth.h
创建中心设备并设置代理
CBCentralManager *manager = [CBCentralManager alloc]init];
一旦设置代理,在程序运行的时候就会调用协议方法
- (void)centralManagerDidUpdateState:(CBCentralManager*)central ;
- 这个方法是判断中心设备是否打开蓝牙设备

二、利用中心设备扫描外部设备
[manager scanForPeripheralsWithServices: option:];
第一个参数表示扫描带有相关服务的外部设备,例如填写@[[CBUUID UUIDWithString:@”需要连接的外部设备的服务的UUID”]] nil 表示扫描全部设备
options @{CBCentralManagerScanOptionAllowDuplicatesKey : YES}
一旦扫描到有外部设备
- centalManager:(CBCentraManager*)centralManager didDiscoverPeripheral:() advertisementData:(NSDictionary*)
- 在这个协议里,我们可以根据我们获取到的硬件的某些条件进行筛选,然后连接我们需要连接的外部设备,例如连接名字带有”**“的外部设备
- if(peripheral.namehasPrefix:@”
**“){
连接设备
manager connectPeripheral:peripheral options:nil];
}
-(void)peripheral: didDiscoverCharacteristicsForService: error: ;

5、扫描到特征之后,我们就可以拿到特征进行读写操作
例如进行读取数据的操作:
if([characteristic.UUID.UUIDStringisEqualToString:@”“]){
peripheral readValueForCharacteristic:characteristic];
}
只要读取了就会进入另一个协议方法

-(void)peripheral: didUpdateValueForCharacteristic:
在这个方法里我们就拿到了我们需要的数据,进行写的操作是:
peripheral writeValue: forCharacteristic: type:

每写一次数据就会进入

-(void)peripheral: didWriteValueForCharacteristc: error:

这个方法会告诉我们,写操作成功与否
外设模式请查看:
http://blog.csdn.net/flover5724059/article/details/73521754

发表评论

表情:
评论列表 (有 0 条评论,272人围观)

还没有评论,来说两句吧...

相关阅读

    相关 AT模式

    一、蓝牙AT模式设置方式 在通电前按住蓝牙模块黑色按钮,接电,当蓝牙指示灯按每隔两秒闪烁一次时进入AT模式; 有3种设置方式: 1.默认设置   模块工作角色:

    相关 AT模式

      一、蓝牙AT模式设置方式   在通电前按住蓝牙模块黑色按钮,接电,当蓝牙指示灯按每隔两秒闪烁一次时进入AT模式;     有3种设置方式: 1.默认设置