Monday, January 3, 2011

DETECTING A SHAKE USING IPHONE SDK


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

No comments:

Post a Comment

Followers