Search code examples
iphoneobjective-ciostimeraccelerometer

How do I implement a timer for this code?


-(void) play
{
    CMMotionManager *motionManager = [[CMMotionManager alloc] init];
    [motionManager startDeviceMotionUpdates];

    BOOL timeReached = NO;

    while(!self.stopButtonPressed)
    {
        if(motionManager.deviceMotion.userAcceleration.y >= ... && motionManager.deviceMotion.userAcceleration.y <= ...)
        {
             //start timer
        }
        while(motionManager.deviceMotion.userAcceleration.y >= ... && motionManager.deviceMotion.userAcceleration.y <= ... && !timeReached)
        {
            if(//check timer & if timer is >=300ms)
            {
              timeReached = YES;
              NSLog(@"acceleration on Y-axis stayed between ... & .. for at least 300ms");
            }
        }
    }
}

Solution

  • It seems like you're going about this the wrong way; instead of running a clock, you should be setting accelerometerUpdateInterval to whatever you're looking for and using startAccelerometerUpdatesToQueue:withHandler: to receive the data.

    From the Apple documentation:

    Handing Motion Updates at Specified Intervals

    To receive motion data at specific intervals, the application calls a “start” method that takes an operation queue (instance of NSOperationQueue) and a block handler of a specific type for processing those updates. The motion data is passed into the block handler. The frequency of updates is determined by the value of an “interval” property.

    Accelerometer. Set the accelerometerUpdateInterval property to specify an update interval. Call the startAccelerometerUpdatesToQueue:withHandler: method, passing in a block of type CMAccelerometerHandler. Accelerometer data is passed into the block as CMAccelerometerData objects.

    Once you've set everything up, let it run. When you've received a completion notice from the block look at the data you've received.