Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Using the Accelerometer on the iPhone, iPod Touch

Obtaining the accelerometer data allows you to build very interesting applications, such as a spirit level, as well as games that depend on motion detection.


advertisement
One of the most innovative features of the iPhone and iPod Touch is the built-in accelerometer. The accelerometer allows the device to detect the orientation of the device and adapts the content to suit the new orientation. For example, when you rotate your device sideways, the Safari Web browser automatically switches the screen to landscape mode so that you now have a wider viewing space.

Similarly, the camera relies on the accelerometer to tell it whether you are taking a picture in portrait or landscape mode. In this article, you learn how to programmatically access the data returned by the accelerometer. Obtaining the accelerometer data allows you to build very interesting applications, such as a spirit level, as well as games that depend on motion detection.

Understanding the Accelerometer



The accelerometer in iPhone and iPod Touch measures the acceleration of the device relative to freefall. A value of 1 indicates that the device is experiencing 1 g of force exerting on it (1 g of force being the gravitational pull of the earth, which your device experiences when it is stationary). The accelerometer measures the acceleration of the device in three different axes: X, Y, and Z. Figure 1 shows the different axes measured by the accelerometer.

Figure 1. The three axes on the iPhone where the accelerometer measures the acceleration.

Figure 2 shows the various readings of the three axes when the device is in the various positions.

Figure 2. The Various Readings of the X, Y, and Z Axes.

If the device is held upright and moved to the right quickly, the value of the X-axis will increase from 0 to a positive value. If it is moved to the left quickly, the value of the X-axis will decrease from 0 to a negative value. If the device is moved upward quickly, the value of the Y-axis will increase from -1.0 to a larger value. If the device is moved download quickly, the value of the Y-axis will decrease from -1.0 to a smaller value.

If the device is lying flat on a table and then dropped, the value of the Z-axis will decrease from -1.0 to a smaller number. If it is moved upward, the value of the Z-axis will increase from -1.0 to a bigger number.

The accelerometer used on the iPhone and iPod Touch gives a -maximum reading of about +/- 2.3G with a resolution of about 0.018 g.

Accessing the Accelerometer

Using Xcode, create a new View-based Application (iPhone) project and name it as Accelerometer.

Add the following statement in bold to the AccelerometerViewController.h file:

? #import <UIKit/UIKit.h> @interface AccelerometerViewController : UIViewController    <UIAccelerometerDelegate> { } @end In the AccelerometerViewController.m file, add the following code in bold: #import "AccelerometerViewController.h" @implementation AccelerometerViewController - (void)viewDidLoad {    UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer];    accel.delegate = self;    accel.updateInterval = 1.0f/60.0f;           [super viewDidLoad]; } - (void)accelerometer:(UIAccelerometer *)acel        didAccelerate:(UIAcceleration *)acceleration {        NSLog(@"x: %g", acceleration.x);    NSLog(@"y: %g", acceleration.y);    NSLog(@"z: %g", acceleration.z); }

Basically, you obtain an instance of the UIAccelerometer class and then set its update interval. Here, you are setting it to update 60 times a minute. For each interval, the accelerometer:didAccelerate: method will be called, where you can obtain the acceleration on the three axes.

Press Command-R to test the application on a real device (you cannot test this on the iPhone Simulator). Move your device and you should see the values for the three axes printed in the Debugger Console window (press Shift-Command-R in Xcode; see Figure 3).

Figure 3. Observing the data printed in the Debugger Console window

Printing out the raw values of the accelerometer data is not very exciting. Let's now modify the application so that you will make use of the accelerometer data to move a tennis ball on screen.

First, prepare an image like the one shown in Figure 4.

Figure 4. An image of a tennis ball.

Drag and drop the image onto the Resources folder of your project (see Figure 5).

Figure 5. Copying the image into the project.

Double-click on the AccelerometerViewController.xib file to edit it in Interface Builder.

Add a UIImageView to the View window and set its Image attribute to tennisball.jpg. Also, set the background color of the View window to black (see Figure 6).

Figure 6. Populating the View window.

In the AccelerometerViewController.h file, add the following code in bold:

#import <UIKit/UIKit.h> @interface AccelerometerViewController : UIViewController    <UIAccelerometerDelegate> {    IBOutlet UIImageView *imageView;    CGPoint delta;    CGPoint translation;    float ballRadius;     } @property (nonatomic, retain) UIImageView *imageView; @end In Interface Builder, control-click and drag the File's Owner item over the UIImageView. Select imageView. In the AccelerometerViewController.m file, add the following code in bold: #import "AccelerometerViewController.h" @implementation AccelerometerViewController @synthesize imageView; - (void)viewDidLoad {    UIAccelerometer *accel = [UIAccelerometer sharedAccelerometer];    accel.delegate = self;    accel.updateInterval = 1.0f/60.0f;    ballRadius = imageView.frame.size.width / 2;    delta = CGPointMake(12.0,4.0);    translation = CGPointMake(0.0,0.0);            [super viewDidLoad]; } - (void)accelerometer:(UIAccelerometer *)acel        didAccelerate:(UIAcceleration *)acceleration {        // NSLog(@"x: %g", acceleration.x);    // NSLog(@"y: %g", acceleration.y);    // NSLog(@"z: %g", acceleration.z);        if (acceleration.x>0) delta.x = 2; else delta.x = -2;    if (acceleration.y>0) delta.y = -2; else delta.y = 2;        [UIView beginAnimations:@"translate" context:nil];        imageView.transform =        CGAffineTransformMakeTranslation(translation.x, translation.y);        translation.x = translation.x + delta.x;    translation.y = translation.y + delta.y;        [UIView commitAnimations];            if (imageView.center.x + translation.x > 320 - ballRadius ||        imageView.center.x + translation.x < ballRadius) {        translation.x -= delta.x;    }    if (imageView.center.y + translation.y > 460 - ballRadius ||        imageView.center.y + translation.y < ballRadius) {        translation.y -= delta.y;    }         } - (void)dealloc {    [imageView release];    [super dealloc]; }

Here, you apply a translation (to move the image) via the UIImageView's transform property. The delta represents the amount to move, both in the x and y-axis.

Press Command-R to test the application on the device. Observe that as you move the device, the tennis ball will move in the same direction as your hand (see Figure 7).

Figure 7. Testing the application on a real device

Summary

In this article, you have seen how to programmatically obtain the accelerometer data from your iPhone and iPod touch. You have also seen how to apply the data and put them to good use. If you have some good ideas on how to make use of the accelerometer data, send them to me at weimenglee@learn2develop.net. Have a rolling good time!


   
Wei-Meng Lee is a Microsoft MVP and founder of Developer Learning Solutions, a technology company specializing in hands-on training on the latest Microsoft technologies. He is an established developer and trainer specializing in .NET and wireless technologies. Wei-Meng speaks regularly at international conferences and has authored and coauthored numerous books on .NET, XML, and wireless technologies. He writes extensively on topics ranging from .NET to Mac OS X. He is also the author of the .NET Compact Framework Pocket Guide, ASP.NET 2.0: A Developer's Notebook (both from O'Reilly Media, Inc.), and Programming Sudoku (Apress). Here is Wei-Meng's blog.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap