Search code examples
iosbluetooth-lowenergynstimer

iOS: Writing to Bluetooth LE device with NSTimer


I'm trying to write a char to my Bluetooth LE device, and so far it has worked, but only when I do it inside the didDiscoverCharacteristicsForService method.

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
    if (error) {
        [self cleanup];
        return;
    }

    for (CBCharacteristic *characteristic in service.characteristics) {
        if ([characteristic.UUID isEqual: CHAR_UUID]) {
            NSLog(@"Discovered characteristic: %@", characteristic);
            [peripheral setNotifyValue:YES forCharacteristic:characteristic];
            _discoveredCharacteristic = characteristic;

            char c;
            count++;
            if (count%2 == 1)
            {
                c = 0x0;
            }
            else
            {
                c = 0x7;
            }

            NSData *data = [NSData dataWithBytes: &c length: 1];
            [_discoveredPeripheral writeValue:data forCharacteristic:_discoveredCharacteristic
                                         type:CBCharacteristicWriteWithResponse];

            NSLog(@"Writing value %@ for characteristic %@", data, _discoveredCharacteristic.UUID);
        }
    }

timer = [NSTimer scheduledTimerWithTimeInterval:2
                                                 target:self selector:@selector(targetMethod:)
                                               userInfo:nil repeats:YES];
        _repeatingTimer = timer;
    }

But when I move the writeValue part into a method triggered by a timer, it no longer writes the value to my device. Why is this? What am I doing wrong?

- (void)targetMethod:(NSTimer*)theTimer{
    char c;
    count++;
    if (count%2 == 1)
    {
        c = 0x0;
    }
    else
    {
        c = 0x7;
    }

    NSData *data = [NSData dataWithBytes: &c length: 1];
    [_discoveredPeripheral writeValue:data forCharacteristic:_discoveredCharacteristic
                                 type:CBCharacteristicWriteWithResponse];

    NSLog(@"Writing value %@ for characteristic %@", data, _discoveredCharacteristic.UUID);
}

I am very new to both iOS and Bluetooth.


Solution

  • I was being dumb, and was closing my connection to the peripheral after writing.