Search code examples
ioscbperipheral

How do I write <1100> or <2200> to the value of a characteristic on my CBPeripheral?


When I NSLog characteristic.value it shows as either <1100> or <2200>. I know this is a hexadecimal. I'm confused as what to write when I'm changing the value.

Any help would be much appreciated.

At the moment I'm doing the following, but getting null when I change the values.

- (IBAction)deviceSwitchPressed:(id)sender {
    if ([sender isOn]) {
        [activePeripheral writeValue:[@"1100" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:switchCharacterictic type:CBCharacteristicWriteWithResponse];
    } else {
        [activePeripheral writeValue:[@"2200" dataUsingEncoding:NSUTF8StringEncoding] forCharacteristic:switchCharacterictic type:CBCharacteristicWriteWithResponse];
    }

    NSLog(@"characteristic.value = %@", switchCharacterictic.value);

}

Solution

  • This is what I use to convert hex string values into data objects.

    NSString *command = hexString;
    command = [command stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSMutableData *commandToSend= [[NSMutableData alloc] init];
    unsigned char whole_byte;
    char byte_chars[3] = {'\0','\0','\0'};
    int i;
    for (i=0; i < [command length]/2; i++) {
        byte_chars[0] = [command characterAtIndex:i*2];
        byte_chars[1] = [command characterAtIndex:i*2+1];
        whole_byte = strtol(byte_chars, NULL, 16);
        [commandToSend appendBytes:&whole_byte length:1];
    }
    

    However writing a value to a characteristic doesn't guarantee that is what will be returned. The peripheral can handle that data in anyway that it wants.