ble 4.0 iOS开发 注意点

发送数据:

      ①string转到data 


-(NSData*)stringToByte:(NSString*)string

{

    

    

    NSString *hexString=[[string uppercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];

    if ([hexString length]%2!=0) {

        return nil;

    }

    Byte tempbyt[1]={0};

    NSMutableData* bytes=[NSMutableData data];

    for(int i=0;i<[hexString length];i++)

    {

        unichar hex_char1 = [hexString characterAtIndex:i]; 两位16进制数中的第一位(高位*16)

        int int_ch1;

        if(hex_char1 >= '0' && hex_char1 <='9')

            int_ch1 = (hex_char1-48)*16;   0 Ascll - 48

        else if(hex_char1 >= 'A' && hex_char1 <='F')

            int_ch1 = (hex_char1-55)*16; A Ascll - 65

        else

            return nil;

        i++;

        

        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)

        int int_ch2;

        if(hex_char2 >= '0' && hex_char2 <='9')

            int_ch2 = (hex_char2-48); 0 Ascll - 48

        else if(hex_char2 >= 'A' && hex_char2 <='F')

            int_ch2 = hex_char2-55; A Ascll - 65

        else

            return nil;

        

        tempbyt[0] = int_ch1+int_ch2;  ///将转化后的数放入Byte数组里

        [bytes appendBytes:tempbyt length:1];

    }

    return bytes;

}


②将数据发送到已经获取的外设服务

 NSString* cancel = @"04";

            NSData* send = [self stringToByte:cancel];

            [_presentPeripheral writeValue:send forCharacteristic:_chosenCh type:CBCharacteristicWriteWithResponse];

            NSLog(@"发送%@",cancel);




接收数据:

①打开相关服务的广播

//很重要  打开广播

    [_presentPeripheral setNotifyValue:YES forCharacteristic:_chosenCh];


②不停监听


    [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(getData) userInfo:nil repeats:YES];

- (void)getData

{

    [_presentPeripheral readValueForCharacteristic:_chosenCh];


}


③外设服务value发生改变的时候的代理方法

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

{

    


    

    NSLog(@"%@",[characteristic.UUID UUIDString]);


    

    const unsigned char *hexBytesLight = [characteristic.value bytes];

    

    int a = hexBytesLight[0] ;//按字节读取的 按要求读取

 

    NSLog(@"%d",a);


//数据操作

    

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值