简体   繁体   中英

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.

我很傻,写完后就关闭了与外围设备的连接。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM