Using the Accelerometer on the iPhone, iPod Touch

Using the Accelerometer on the iPhone, iPod Touch

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 @interface AccelerometerViewController : UIViewController      {}@endIn 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 windowPrinting 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 @interface AccelerometerViewController : UIViewController      {    IBOutlet UIImageView *imageView;    CGPoint delta;    CGPoint translation;    float ballRadius;    }@property (nonatomic, retain) UIImageView *imageView;@endIn 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 [email protected] 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 ( + translation.x > 320 - ballRadius || + translation.x < ballRadius) {        translation.x -= delta.x;    }    if ( + translation.y > 460 - ballRadius || + 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


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 [email protected]. Have a rolling good time!

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes