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

  • Today's agile organizations pose operations teams with a tremendous challenge: to deploy new releases to production immediately after development and testing is completed. To ensure that applications are deployed successfully, an automatic and transparent process is required. We refer to this process as Zero Touch Deployment™. This white paper reviews two approaches to Zero Touch Deployment--a script-based solution and a release automation platform. The article discusses how each can solve the key …

  • On-demand Event Event Date: December 18, 2014 The Internet of Things (IoT) incorporates physical devices into business processes using predictive analytics. While it relies heavily on existing Internet technologies, it differs by including physical devices, specialized protocols, physical analytics, and a unique partner network. To capture the real business value of IoT, the industry must move beyond customized projects to general patterns and platforms. Check out this webcast and join industry experts as …

Most Popular Programming Stories

More for Developers

RSS Feeds