Use CoreMotion with Accelerometer

PDF for offline use
Sample Code:
Related SDKs:

Let us know how you feel about this


0/250

This recipe shows how to use the Core Motion framework to receive data from the accelerometer.

Recipe

Create an instance of CoreMotion.CMMotionManager, and begin listening to updates from the Accelerometer with the method StartAccelerometerUpdates:

The following code snippet will display the accelerometer data for each axis in UILabels:

motionManager = new CMMotionManager ();
motionManager.StartAccelerometerUpdates (NSOperationQueue.CurrentQueue, (data, error) =>
{
       this.lblX.Text = data.Acceleration.X.ToString ("0.00000000");
       this.lblY.Text = data.Acceleration.Y.ToString ("0.00000000");
       this.lblZ.Text = data.Acceleration.Z.ToString ("0.00000000");
});

The first parameter, data is a CMAccelerometerData instance holding the accelerometer data for the event.

Additional Information

The CoreMotion.CMMotionManager class is a gateway to the motion services provided by iOS. An application should only have a single instance of the CMMotionManager class.

The iOS simulator has no support for the features from Core Motion – the code may only be tested on a device.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.