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:




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.




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.




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