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: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • VMware vCloud® Government Service provided by Carpathia® is an enterprise-class hybrid cloud service that delivers the tried and tested VMware capabilities widely used by government organizations today, with the added security and compliance assurance of FedRAMP authorization. The hybrid cloud is becoming more and more prevalent – in fact, nearly three-fourths of large enterprises expect to have hybrid deployments by 2015, according to a recent Gartner analyst report. Learn about the benefits of …

Most Popular Programming Stories

More for Developers

RSS Feeds