How To Use Accelerometer In iPhone?

This is going to be a very simple example of using the accelerometerto receive input.We are using Quartz 2D in this application for the sake of simplicity and reduce the amount of code that’s unreleated to using the accelerometer.

Step 1: In Xc0de,create a new project using the view-based application template, and call this one Ball. Now single click the classes folder, and select New File… from the File menu . Select UIViewsubclass from the Cocoa Touch category, and name the new file BallView.m.

Step 2: Double click .xib file to open the file in Interface Builder. Single click the View icon, and use the identity inspector to change the view’s class from UIView to BallView. Next switch to the attribute inspector, and change the view’s background color to black. After control drag from the File’s Owner icon to thr Ball View icon, and select the view outlet . Save the nib, close it, and go back to Xcode.

Step 3: All we need to do here is conform the class to the UIAccelerometerDelegate Protocol, make the following change:


#define kUpdateInterval (1.0f/60.0f)
#import <uikit/UIKit.h>

@interface BallViewController : UIViewController {




Step 4: In viewDidLoad method we are declaring a much higher update interval of 60 times a second. Down in the accelerometer:didAccelerometer:method, we pass the acceleration object into our view and then call a method named draw, which updates the position of the ball in the view based on acceleration and the amount of time that has passed since the last update.


 - (void)viewDidLoad {
       UIAccelerometer *accelerometer = [UIAccelerometer sharedAccelerometer];
       accelerometer.delegate = self;
       accelerometer.updateInterval = kUpdateInterval;
      [super viewDidLoad];

#pragma mark-
-(void)accelerometer:(UIAccelerometer *)accelerometer
didAccelerate:(UIAcceleration *)acceleration
[(BallView *)self.view setAcceleration:acceleration];
[(BallView *)self.view draw];



Step 5: We are handling the current Point property manually . We’ll look at that method in a moment. Let’s look at the first method in the class, initWithCoder:. Recall that when you load a view from a nib, that class’s init or initWithFrame: methods will never get called. Nib files contain archive objects, so any instances loaded from nib will get initialized using the initWithCoder: method.


- (id)initWithCoder:(NSCoder *)coder {
if (self = [super initWithCoder:coder]) {
// Initialization code
self.image = [UIImage imageNamed:@"Ball.png"];
self.currentPoint = CGPointMake((self.bounds.size.width/2.0f) +
(image.size.width/2.0f), (self.bounds.size.height/ 2.0f)
+ (image.size.height/2.0f));
ballXVelocity = 0.0f;
ballYVelocity = 0.0f;
return self;

- (void)drawRect:(CGRect)rect {
// Drawing code
[image drawAtPoint:currentPoint];

-(CGPoint)currentPoint {
return currentPoint;

-(void)setCurrentPoint:(CGPoint)newPoint {
previousPoint = currentPoint;
currentPoint = newPoint;

if(currentPoint.x < 0){ currentPoint.x = 0; ballXVelocity = 0; } if(currentPoint.y < 0){ currentPoint.y = 0; ballYVelocity = 0; } if(currentPoint.x > self.bounds.size.width - image.size.width){
currentPoint.x = self.bounds.size.width - image.size.width;
ballXVelocity = 0;

if(currentPoint.y > self.bounds.size.width - image.size.width){
currentPoint.y = self.bounds.size.width - image.size.width;
ballYVelocity = 0;

CGRect currentImageRect = CGRectMake(currentPoint.x
, currentPoint.y ,
currentPoint.x + image.size.width,
currentPoint.y + image.size.height);

CGRect previousImageRect = CGRectMake(previousPoint.x
, previousPoint.y,
previousPoint.x + image.size.width,
previousPoint.y + image.size.height);
[self setNeedsDisplayInRect:CGRectUnion(currentImageRect,

static NSDate *lastDrawTime;

if(lastDrawTime != nil){
NSTimeInterval secondsSinceLastDraw = -([lastDrawTime timeIntervalSinceNow]);

ballYVelocity = ballYVelocity + -(acceleration.y
* secondsSinceLastDraw);
ballXVelocity = ballXVelocity + acceleration.x
* secondsSinceLastDraw;

GFloat xAcceleration = secondsSinceLastDraw * ballXVelocity
* 500;
CGFloat yAcceleration = secondsSinceLastDraw * ballYVelocity
* 500;

self.currentPoint = CGPointMake(self.currentPoint.x + xAcceleration,
self.currentPoint.y +yAcceleration);
[lastDrawTime release];
lastDrawTime = [[NSDate alloc] init];




Step 6: Try to compile the application will lunch, and you should be able to control the movement of the ball by tilting the phone. when the ball gets to an edge of the screen, it should stop.

Figure 1: The Rolling marble application, roll a marble around the screen.

You can downloaded SourceCode from here Ball 2

Leave a Comment:

honkj says August 13, 2010

you’ve got a typo in the code: deidAccelerate should be didAccelerate.

Sushant says August 17, 2010

Thanks for your comment!!! I have changed in the post.

Larry says September 14, 2010

How do you suggest we have an accelerometer program run consistently, monitoring accelerometer output?



Add Your Reply