Home > Articles > Mobile Application Development & Programming

  • Print
  • + Share This
This chapter is from the book

Recipe: Using Acceleration to Locate “Up”

The iPhone provides three onboard sensors that measure acceleration along the iPhone’s perpendicular axes: left/right (X), up/down (Y), and front/back (Z). These values indicate the forces affecting the iPhone, from both gravity and user movement. You can get some neat force feedback by swinging the iPhone around your head (centripetal force) or dropping it from a tall building (freefall). Unfortunately, you might not recover that data after your iPhone becomes an expensive bit of scrap metal.

To subscribe an object to iPhone accelerometer updates, set it as the delegate. The object set as the delegate must implement the UIAccelerometerDelegate protocol:

[[UIAccelerometer sharedAccelerometer] setDelegate:self]

When assigned, your delegate receives accelerometer:didAccelerate: callback messages, which you can track and respond to. The UIAcceleration structure sent to the delegate method consists of floating-point values for the x, y, and z axes. Each value ranges from –1.0 to 1.0:

float x = acceleration.x;
float y = acceleration.y;
float z = acceleration.z;

Recipe 1-3 uses these values to help determine the “up” direction. It calculates the arctangent between the X and Y acceleration vectors, returning the up-offset angle. As new acceleration messages are received, the recipe rotates a UIImageView instance with its picture of an arrow, which you can see in Figure 1-1, to point up. The real-time response to user actions ensures that the arrow continues pointing upward, no matter how the user reorients the phone.

Recipe 1-3. Catching Acceleration Events

- (void)accelerometer:(UIAccelerometer *)accelerometer
    didAccelerate:(UIAcceleration *)acceleration
{
    // Determine up from the x and y acceleration components
    float xx = -acceleration.x;
    float yy = acceleration.y;
    float angle = atan2(yy, xx);
    [arrow setTransform:
        CGAffineTransformMakeRotation(angle)];
}


- (void) viewDidLoad
{
    // Initialize the delegate to start catching accelerometer events
    [UIAccelerometer sharedAccelerometer].delegate = self;
}
Figure 1-1

Figure 1-1. A little math recovers the “up” direction by performing an arctan function using the x and y force vectors. In this example, the arrow always points up, no matter how the user reorients the iPhone.

  • + Share This
  • 🔖 Save To Your Account