Read values of the accelerometer

All modern iOS devices includes a accelerometer, which can detect the motion of the device. The accelerometer provides motion values over the x,y and z-axis. In this tutorial we will read this values and display them on the screen.

Open Xcode and create a new Single View Application. For product name, use AccelerometerDemo and then fill out the Organization Name, Company Identifier and Class Prefix fields with your customary values. Make sure only iPhone is selected in Devices, and that the Use Storyboards checkbox is deselected and Use Automatic Reference Counting checkbox is selected.

In ViewController.m in the interface section, declare the following properties.


@interface ViewController ()

@property (nonatomic, strong) CMMotionManager *motionManager;
@property (nonatomic, strong) IBOutlet UILabel *xAxis;
@property (nonatomic, strong) IBOutlet UILabel *yAxis;
@property (nonatomic, strong) IBOutlet UILabel *zAxis;


The CMMotionManager object acts as a gateway to the motion services provided by iOS. The other properties are needed to update the Labels with the axes values. Go to ViewController.xib and add 3 UILabels to the main View.

Ctrl + Drag from the Label to the File's Owner and make the connection with the corresponding properties.

Change the viewDidLoad method to


- (void)viewDidLoad 
[super viewDidLoad];

self.motionManager = [[CMMotionManager alloc] init];
self.motionManager.accelerometerUpdateInterval = 1;

if ([self.motionManager isAccelerometerAvailable])
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[self.motionManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
self.xAxis.text = [NSString stringWithFormat:@"%.2f",accelerometerData.acceleration.x];
self.yAxis.text = [NSString stringWithFormat:@"%.2f",accelerometerData.acceleration.y];
self.zAxis.text = [NSString stringWithFormat:@"%.2f",accelerometerData.acceleration.z];
} else
NSLog(@"not active");

First we initialize the CMMotionManager object, then we check if the accelerometer is available on the iOS device. We use the startAccelerometerUpdatesToQueue:withHandler method to get updates every secondd of the accelerometer. Then we update our UILables with the coresponding values on the main queue.

Because the iOS Simulator doesn't have a simulated accelerometer, you can run this app only on a device. Build and Run, and move the Device into the different axes. The values should be between -1.00 and 1.00

You can download the source code of the AccelerometerDemo at the ioscreator repository on github.