Accelerometer

0
131

All Windows Phone 7 physical devices include an accelerometer that measures acceleration forces due to gravity, or due to forces caused by moving the device, and indicates the orientation of the device. The Accelerometer API in the operating system of the device can be accessed by Microsoft® Silverlight® for Windows Phone and XNA® for Windows Phone applications.

To use the Accelerometer API, you must do the following:

  • Add a reference to the assembly Microsoft.Devices.Sensors to your project.
  • Instantiate an accelerometer.
  • Specify a callback in the form of an event handler or lambda expression that will receive the data.
  • Start the accelerometer.

The following code example shows how to use the Accelerometer API.

C#
var accel = new Accelerometer();
accel.ReadingChanged += new EventHandler
<AccelerometerReadingEventArgs>(Accelerometer_ReadingChanged);
try
{
accel.Start();
}
catch
{
// Error starting the accelerometer.
}

You can then access the readings as they change in your event handler. Remember that the event handler runs on a different thread from the user interface (UI), so you must invoke a method on the UI thread if you want to update the UI with the discovered values.

C#
void Accelerometer_ReadingChanged(object sender,
AccelerometerReadingEventArgs e)
{
string xCoordinate = e.X.ToString(“0.00”);
// Acceleration in the X direction.
string yCoordinate = e.Y.ToString(“0.00”);
// Acceleration in the Y direction.
string zCoordinate = e.Z.ToString(“0.00”);
// Vertical acceleration.
DateTimeOffset time = e.Timestamp;
// When this reading was obtained.
}

The values returned are of type Double and indicate the force applied in the three planes of the device. When it is laid flat on its back, they will return values very close to X=0, Y=0, Z=-1. When held vertically, they return approximately X=0, Y=-1, Z=0. Figure 1 illustrates how the values indicate the orientation of forces on the device.

The orientation of forces detected by the accelerometer

The accelerometer also exposes the State property, which returns a value from the SensorState enumeration indicating the current state of the accelerometer. Typical values are Initializing, Ready, NoData, NoPermissions, Disabled, and NotSupported.

To stop the accelerometer when you no longer require it, which signifi cantly reduces the processing load on the device, call the Stop method.

For more information, see “Accelerometer for Windows Phone” on MSDN (http://msdn.microsoft.com/en-us/library/ff431793(VS.92). aspx). You can also download a code sample that demonstrates using the Accelerometer API from “Code Samples for Windows Phone” on MSDN (http://msdn.microsoft.com/en-us/library/ff431744(VS.92).
aspx).