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

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • Not all enterprise applications are created equal. Sophisticated applications need developer support but other more basic apps do not. With the right tools, everyone is a potential app developer with ideas and a perspective to share. Trends such as low-code development and model driven development are fundamentally changing how and who creates applications. Is your organization ready? Read this report and learn: The seven personas of enterprise app delivery How application ownership is spreading to the …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds