22

I need to detect when the gyroscope / accelerometer is activated a certain amount. Basically to detect when there is movement of the device. I don't know anything about Core Motion.

Maybe someone can direct me to a starters tutorial or something.

Thanks in advance.

2 Answers 2

35

I think you have to use Core Motion. The good news is that it is not that hard to use for your problem domain. Start reading the Event Handling Guide especially the section Handling Processed Device-Motion Data. If you are just interested in knowing that a slight motion was made, as you stated, you can omit rotation handling and narrow signal processing on CMDeviceMotion.userAcceleration. This is because every rotation results in accelerometer signals as well.

Create a CMDeviceMotionHandler as described in startDeviceMotionUpdatesToQueue:withHandler: Your CMDeviceMotionHandler should do something like:

float accelerationThreshold = 0.2; // or whatever is appropriate - play around with different values
CMAcceleration userAcceleration = deviceMotion.userAcceleration;
if (fabs(userAcceleration.x) > accelerationThreshold) 
    || fabs(userAcceleration.y) > accelerationThreshold
    || fabs(userAcceleration.z) > accelerationThreshold) {
    // enter code here
}

Basically that's it. Bear in mind that every acceleration will have a counterpart. That means, if you apply a force to move (i.e. accelerate) the device to the right, there will be a counterpart for deceleration to stop the motion and let that the device rest at the new position. So your if condition will become true twice for every single motion.

4
  • The link you gave is excellent! Even though I've been searching on motion readings, and read all relevant class references - I just couldn't a find a summary like that - thanks! Commented Aug 7, 2011 at 6:14
  • Thank you for explaining in a simple and easy to understand way :)
    – Luqman
    Commented May 30, 2013 at 14:46
  • 1
    This link is dead "Handling Processed Device-Motion Data" Can you please update the link?
    – bpolat
    Commented Aug 21, 2014 at 16:43
  • 1
    At the time of this comment, you can find a cached copy of that article here.
    – henryaz
    Commented Sep 29, 2014 at 16:30
2

In viewDidAppear, become the first responder:

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self becomeFirstResponder];
}

And make sure you can be first responder:

- (BOOL)canBecomeFirstResponder {
    return YES;
}

Then you can implement the motion detection.

- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event
{
    if (event.subtype == UIEventTypeMotion){
        //there was motion
    }
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.