Search code examples
swiftbluetooth-lowenergyaccelerometergyroscopemagnetometer

Swift Sensortag 2.0 Write Bits to BLE


Pretty basic question here:

I'm currently trying to control a sensortag 2.0 via Swift 3.0.

I'm trying to simultaneously turn on the acc, gyro, and magnetometer.

According to Texas Instruments documentation, the following applies for the IMU:

Axis enable bits:gyro-z=0,gyro-y,gyro-x,acc-z=3,acc-y,acc-x,mag=6 Range: bit 8,9

I have written "0x023F" in the following manner, which turns on the gyro and the accelerometer with great success.

                let value = OperationDataHolder(data:[0x023F])
                var parameter = 0x023F
                let data = NSData(bytes: &parameter, length: 2)
                self.sensorTagPeripheral.writeValue(data as Data, for: thisCharacteristic, type: CBCharacteristicWriteType.withResponse)

However, I'm not able to figure out the value to write to turn turn on all 3 units simultaneously. Would someone be able to provide me with this value?

Thanks!


Solution

  • When you convert the current value you are using (0x023F) to binary, you get 0b1000111111. Each of the bits represents the on/off (on=1/off=0) state of a given sensor component.

    If you read the binary number from right to left, and map each bit by referencing the table below, you will see that the gyro z/y/x and accelerometer z/y/x are all enabled. If you want to enable the magnetometer, simply change 'bit 6' to a '1' and convert that binary number to a hexadecimal number.

    So, Google says: 0b1001111111 is 0x027F in hexadecimal

    Mapping:
    bit 0 => gyro z-axis
    bit 1 => gyro y-axis
    bit 2 => gyro x-axis
    bit 3 => acc z-axis
    bit 4 => acc y-axis
    bit 5 => acc x-axis
    bit 6 => mag (enables all axes)
    bit 7 => Wake-on-motion enable
    bits 8 & 9 => Accelerometer range
    bits 10-15 => not used

    For more info about the mapping (i.e. what bits 8 & 9 do), see the Sensor Tag Wiki Page