Developing for the Windows Phone Sensors

Introduction

Windows Phone devices sport a multitude of sensors, which help detect movement of the device itself. Microsoft has even provided sensor support within the Windows Phone platform itself to enable programmatic access to this information from applications. In this article, we will explore ways to access each of the sensor's readings in a Windows Phone application. Knowledge of these sensors can be used to develop life-like interactive applications like motion-controlled games.

Windows Phone supports three types of physical sensors on each device.

  • accelerometer
  • compass
  • gyroscope

Each of these sensor measures different forces:

  • Accelerometer senses the direction in which the device is moving by measuring the force being applied on the device. The force can then be decomposed to represent in a 3-dimensional format (X, Y and Z axes).
  • Compass (also called magnetometer) senses the deviation of the device's angle compared to the earth's magnetic north.
  • Gyroscope senses the rotational velocity of the device along the axes and can be used to determine the orientation of the device.

Each of the sensors is susceptible to errors when the raw data is consumed as-is. To make things simpler, Microsoft has provided a Motion class in the Microsoft.Devices.Sensors namespace. The use of Motion class is recommended in typical use case scenarios.

Using the Sensors Programmatically in a Windows Phone Application

The built-in support in the Windows Phone platform for sensors makes it extremely easy to use their data in a Windows Phone application.

To start with, create a new Windows Phone project (let's call it WindowsPhoneSensorDemo). Add a project reference to the Microsoft.Devices.Sensors.dll in the project references dialog.

Windows Phone project references dialog
Figure 1: Windows Phone project references dialog

Also, add a reference to the Microosft.Xna.Framework.dll because we will be using a class from that namespace as well.

Add a few controls as shown in the diagram below

Add a few controls
Figure 2: Add a few controls

On the top, add a textbox (name it textBoxStatus).

Add 3 pairs of textblocks and textboxes, each corresponding to the X, Y and Z coordinates.

Finally, add a button called buttonReset, which will be used to reset the values of the textboxes to empty.

Now, open up MainPage.xaml.cs and add the following line in the "using" declaratives section.

using Microsoft.Devices.Sensors;

Next, add a variable of type Accelerometer to the MainPage class.

public partial class MainPage : PhoneApplicationPage
    {
        Accelerometer myAccelerometer;
        // Constructor
        public MainPage()

Next, add the code to update the status of the textBoxstatus with an error in case Accelerometer is not supported. This might apply when the phone is in a locked state.

public MainPage()
        {
            InitializeComponent();
 
            if (!Accelerometer.IsSupported)
            {
                textBoxStatus.Text= "Accelerometer is not supported";
            }
            myAccelerometer = new Accelerometer();
            myAccelerometer.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<AccelerometerReading>>(accl_CurrentValueChanged);
            myAccelerometer.Start();
            
        }

If accelerometer support is available, we create a new instance of the accelerometer class and wire up its CurrentValuechanged event. Finally, we call the Start method on the accelerometer (to start listening to the events being fired from the accelerometer sensor).

Next, we add code to implement the event handler for the CurrentValueChanged event on the accelerometer.

void accl_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
        {
            Dispatcher.BeginInvoke(() => UpdateStatus(e.SensorReading));
        }

Finally, we add code to update the textboxes with the values from the sensor. Also, we implement the code to reset the values of the textboxes when the Reset button is clicked.

void UpdateStatus(AccelerometerReading reading)
        {
  
            textBoxX.Text = reading.Acceleration.X.ToString("0.00");
            textBoxY.Text = reading.Acceleration.Y.ToString("0.00");
            textBoxZ.Text = reading.Acceleration.Z.ToString("0.00");
        }
 
        private void buttonReset_Click(object sender, RoutedEventArgs e)
        {
            textBoxX.Text = "";
            textBoxY.Text = "";
            textBoxZ.Text = "";
        }

Now, compile the application and launch it under the debugger. If you are having issues compiling the code, you can download the sample code below.

Now, run the application. If you are running in the emulator, you can click on the >> icon on the emulator to open the Additional tools option and test out the accelerometer.

Additional tools option
Figure 3: Additional tools option

Drag the red dot on the phone to see how the values of the accelerometer sensors are captured and rendered on the application window. If you want to simulate a shake, you can click the Play button on the right and see the impact of the shake on the values captured by the sensor.

Click the Play button to simulate a shake
Figure 4: Click the Play button to simulate a shake

Summary

In this article, we learned how we can build a windows phone application that uses sensors. I hope you have found the information useful.



About the Author

Vipul Vipul Patel

Vipul Patel is a Software Engineer currently working at Microsoft Corporation, working in the Office Communications Group and has worked in the .NET team earlier 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

  • Live Event Date: November 20, 2014 @ 2:00 p.m. ET / 11:00 a.m. PT Are you wanting to target two or more platforms such as iOS, Android, and/or Windows? You are not alone. 90% of enterprises today are targeting two or more platforms. Attend this eSeminar to discover how mobile app developers can rely on one IDE to create applications across platforms and approaches (web, native, and/or hybrid), saving time, money, and effort and introducing apps to market faster. You'll learn the trade-offs for gaining long …

  • Live Event Date: October 29, 2014 @ 11:00 a.m. ET / 8:00 a.m. PT Are you interested in building a cognitive application using the power of IBM Watson? Need a platform that provides speed and ease for rapidly deploying this application? Join Chris Madison, Watson Solution Architect, as he walks through the process of building a Watson powered application on IBM Bluemix. Chris will talk about the new Watson Services just released on IBM bluemix, but more importantly he will do a step by step cognitive …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds