发送数据:
①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];
}
- (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);
//数据操作
}