Using the Accelerometer in Your Windows Phone Application

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Introduction

An accelerometer can report the direction and magnitude of the force being applied to it.

The force is represented along three dimensions – ‘x’ is horizontal, ‘y’ is vertical, and ‘z’ is perpendicular to the plane. Every dimension value can range from ‘-2’ to ‘2’.

When the phone is on a flat surface, the values will be x:0, y:0 and z:-1.

All Windows Phones have built in accelerometers. Whenever there is a movement of the device, the values of X, Y and Z can help locate the direction in which the phone has moved.

Accelerometer Basics

Windows Phone framework has robust support for accelerometer in the form of the Accelerometer class, which resides in the Microsoft.Devices.Sensors namespace in the Microsoft.Devices.Sensors assembly.

The ReadingChanged event on the Accelerometer class is fired whenever the device senses movement.

Hands-On

Create a new Visual Studio project called AccelerometerDemo.

Create a new Visual Studio project
Create a new Visual Studio project

When prompted, choose Windows Phone 7.1 and click OK.

Choose Windows Phone 7.1
Choose Windows Phone 7.1

Add a reference to the Microsoft.Devices.Sensors.dll

Microsoft.Devices.Sensors.dll
Microsoft.Devices.Sensors.dll

In MainPage.xaml.cs, add a “using” statement for Microsoft.Device.Sensors namespace.

using Microsoft.Devices.Sensors;

Add three textboxes and two buttons on MainPage.xaml.

Name the buttons, Start and Stop.

Add an instance of the accelerometer class as a variable on MainPage.xaml and initialize it in the constructor of MainPage.xaml.

    public partial class MainPage : PhoneApplicationPage
    {
        Accelerometer myAccelerometer;
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            myAccelerometer = new Accelerometer();
        }
    }

Now, wire up the click event on the Start button to start getting readings from the accelerometer.

private void buttonStart_Click(object sender, RoutedEventArgs e)
        {
            myAccelerometer.Start();
        }

Next, wire up the click event on the Stop button to stop getting readings from the Accelerometer.

private void buttonStop_Click(object sender, RoutedEventArgs e)
        {
            myAccelerometer.Stop();
        }

Next, we add an event handler for the ReadingChanged event and wire it up whenever we start and stop the accelerometer.

private void buttonStart_Click(object sender, RoutedEventArgs e)
        {
            myAccelerometer.Start();
            myAccelerometer.ReadingChanged += myAccelerometer_ReadingChanged;
        }


private void buttonStop_Click(object sender, RoutedEventArgs e)
        {
            myAccelerometer.Stop();
            myAccelerometer.ReadingChanged -= myAccelerometer_ReadingChanged;
        }

We finally implement the event handler. To keep it simple, we will type the value we receive from the accelerometer in the textboxes.

Since the events are being received on the main thread, we will need to create a delegate to process these events on a separate thread.

void
myAccelerometer_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {

           
this.Dispatcher.BeginInvoke(delegate()
            {

             
  textBoxX.Text = e.X.ToString();

                textBoxY.Text = e.Y.ToString();

                textBlockZ.Text = e.Z.ToString();

            }

            );

        }


Finally, we are ready to test what we have built. Our complete code is shown below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Devices.Sensors;
 
namespace AccelerometerDemo
{
    public partial class MainPage : PhoneApplicationPage
    {
        Accelerometer myAccelerometer;
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            myAccelerometer = new Accelerometer();
        }
 
        private void buttonStart_Click(object sender, RoutedEventArgs e)
        {
            myAccelerometer.Start();
            myAccelerometer.ReadingChanged += myAccelerometer_ReadingChanged;
        }
 
        void myAccelerometer_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {
            this.Dispatcher.BeginInvoke(delegate()
            {
                textBoxX.Text = e.X.ToString();
                textBoxY.Text = e.Y.ToString();
                textBlockZ.Text = e.Z.ToString();
            }
            );
        }
 
        private void buttonStop_Click(object sender, RoutedEventArgs e)
        {
            myAccelerometer.Stop();
            myAccelerometer.ReadingChanged -= myAccelerometer_ReadingChanged;
        }
    }
}

If you are having problems following along and building the project, you can download a copy of the source code below.

When we run the application (on a real device) and we click the start button, we will immediately start seeing that the textboxes are updated for every physical movement encountered by the device.

If you are running on the emulator, you have the option to exercise the accelerometer using “>>” key on the emulator.

Summary

In this article, we learned how to tap into the accelerometer to get the information about the direction and magnitude of the force felt by a Windows Phone device and use that to make better applications.

About the Author

Vipul Patel is a Program Manager currently working at Amazon Corporation. He has formerly worked at Microsoft in the Lync team and in the .NET team (in the Base Class libraries and the Debugging and Profiling team). He can be reached at [email protected]

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read