Detecting a shake using iPhone SDK
July 28, 2009
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
- Refresh the current view
- Go to next/previous screen
- Start editing
- Shuffle
- 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
Entry Filed under: Geeky stuff. Tags: iPhone, Tutorial.
3 Comments Add your own
Leave a Comment
Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
Trackback this post | Subscribe to the comments via RSS Feed
1.
Craig | September 5, 2009 at 12:33 am
This detects a sudden acceleration, not a shake?
2. [todo Austin] 奧斯丁。土豆 » Blog Archive » [iPhone] 透過三軸感應縮放地圖 | May 23, 2010 at 12:20 pm
[...] 偵測Shake:Link [...]
3.
Anonymous | June 30, 2010 at 6:49 am
Did not work idk wat i did wrong but i get six errors because some things arent declared.