Detecting a shake using iPhone SDK

July 28, 2009 at 6:22 pm 3 comments

Accelerometer has added an all new dimension to the iPhone. There is no limit on how we can use the accelerometer API in iPhone SDK. The following are some of the well known simple uses of shake/motion detection

  1. Refresh the current view
  2. Go to next/previous screen
  3. Start editing
  4. Shuffle
  5. and the list goes on

Today lets check out how we can detect a simple shake using the API

In order to detect a shake, the class needs to conform to the protocol UIAccelerometerDelegate and reimplement the optional method (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration.

- (void) accelerometer: (UIAccelerometer *)accelerometer didAccelerate: (UIAcceleration *)acceleration {
    if (self.lastAcceleration) {
        if (!shakeDetected && IsDeviceShaking(self.lastAcceleration, acceleration, 0.7)) {
            shakeDetected = YES;
            //SHAKE DETECTED. WRITE YOUR CODE HERE.
        } else if (shakeDetected && !IsDeviceShaking(self.lastAcceleration, acceleration, 0.2)) {
            shakeDetected = NO;
        }
    }
    self.lastAcceleration = acceleration; 
}

Note that in the class which re-implements this method we declare an UIAcceleration object named lastAcceleration and a BOOLEAN variable called shakeDetected. We also need to write a static method named IsDeviceShaking

Here’s the implementation of function IsDeviceShaking:

static BOOL IsDeviceShaking(UIAcceleration* last, UIAcceleration* current, double threshold) {
    double deltaX = fabs(last.x - current.x);
    double deltaY = fabs(last.y - current.y);
    double deltaZ = fabs(last.z - current.z);
    return (deltaX > threshold && deltaY > threshold) ||
           (deltaX > threshold && deltaZ > threshold) ||
           (deltaY > threshold && deltaZ > threshold);
}

The above function returns TRUE if the device is shook in any of the 2 axis and the shake is greater than the threshold. One can increase or decrease the sensitivity by changing the threshold.

Just put these pieces together and you can detect shake in any screen of your application you want.

Please let me know your feedback/suggestions

Advertisements

Entry filed under: Geeky stuff. Tags: , .

Using iPhone SDK MapKit Framework – A tutorial Freelancers versus Employees: The Difference

3 Comments Add your own

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


TinyTweets

Feeds


%d bloggers like this: