Home > Uncategorized > Using the iPhone accelerometer

Using the iPhone accelerometer

March 14th, 2009

I've discovered that it is quite easy to gain access to the iPhone accelerometer. Below are some simple code fragments that can be utilized to gain access to the sensor:

In the header of an Objective-C interface you need to add the protocol for the accelerometer. In my example I am going to add it to an EAGLView, which is a subclass of UIView used for OpenGL ES:

 
@interface EAGLView : UIView <UIAccelerometerDelegate> {
   //your code here
}
//your methods
- (void)accelerometer:(UIAccelerometer *)accelerometer
      didAccelerate:(UIAcceleration *)acceleration;
@end
 

In your implementation file you simply need to add the following lines in an init function, or in the case of EAGLView you could add them in initWithCoder:

 
//You may need to change the interval to optimize your app's performance:
[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(0.1f)];
[[UIAccelerometer sharedAccelerometer] setDelegate:self];
 

The final line you need to add to the implementation file is the function we added to the header:

 
- (void) accelerometer:(UIAccelerometer*)
accelerometer didAccelerate:(UIAcceleration*)acceleration {
	NSLog(@"X: %g, Y: %g, Z: %g", acceleration.x,
             acceleration.y, acceleration.z);
}
 

rjett Uncategorized

  1. No comments yet.
  1. No trackbacks yet.