Using the Accelerometer in Your Windows Phone Application

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 vipul_d_patel@hotmail.com



Related Articles

Downloads

Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Savvy enterprises are discovering that the cloud holds the power to transform IT processes and support business objectives. IT departments can use the cloud to redefine the continuum of development and operations—a process that is becoming known as DevOps. Download the Executive Brief DevOps: Why IT Operations Managers Should Care About the Cloud—prepared by Frost & Sullivan and sponsored by IBM—to learn how IBM SmartCloud Application services provide a robust platform that streamlines …

  • Java developers know that testing code changes can be a huge pain, and waiting for an application to redeploy after a code fix can take an eternity. Wouldn't it be great if you could see your code changes immediately, fine-tune, debug, explore and deploy code without waiting for ages? In this white paper, find out how that's possible with a Java plugin that drastically changes the way you develop, test and run Java applications. Discover the advantages of this plugin, and the changes you can expect to see …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds