31 Days of Windows Phone | Day #11: Accelerometer

This post is Day #11 in a series called the 31 Days of Windows Phone.

Yesterday, we talked about the software-based keyboard on Windows Phone.  Today, we’re going to talk about the hardware-based accelerometer, and how we can take advantage of the information it provides.

What is an accelerometer?

For lack of a better definition, an accelerometer is a sensor in the Windows Phone devices that measures the acceleration on 3 axes (X, Y, Z), relative to freefall.  In addition to a timestamp, the values are expressed in G-forces (1G = 9.81 m/s2).  What this means is that if the phone is lying face-up on a perfectly flat surface, the Z axis would read –1.0, and the other two axes would read 0.  Here’s a quick illustration showing the different values (thanks to WindowsTeamBlog for the image):

accelerometeraxes

 

How do I get values from the WP7 Accelerometer?

Thankfully, this is pretty simple.  The one major complication is that we have some thread management to handle, but it’s really simple stuff.  Here’s what we need to do:

  1. Instantiate a new Accelerometer object.
  2. Create a new ReadingChanged() event handler to monitor the changes in data.
  3. Pass the results of that event back to our page’s thread (the event fires on a different thread).
  4. Use the data values in our application.

Here’s the entirety of my MainPage.xaml.cs file for this example.  You’ll see that I have created three TextBlocks (XText, YText, and ZText) on my MainPage.xaml file, so that I can write the values to the screen.  Also notice that I had to add a new reference to Microsoft.Devices.Sensors to get access to the Accelerometer.

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 Day11_Accelerometer
{
	public partial class MainPage : PhoneApplicationPage
	{
		Accelerometer acc = new Accelerometer();
		
		// Constructor
		public MainPage()
		{
			InitializeComponent();
			acc.ReadingChanged += new EventHandler<AccelerometerReadingEventArgs>(acc_ReadingChanged);
			acc.Start();
		}

		void acc_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
		{
			Deployment.Current.Dispatcher.BeginInvoke(() => ThreadSafeAccelerometerChanged(e));
		}

		void ThreadSafeAccelerometerChanged(AccelerometerReadingEventArgs e)
		{
			XText.Text = e.X.ToString("0.000");
			YText.Text = e.Y.ToString("0.000");
			ZText.Text = e.Z.ToString("0.000");
		}
	}
}

Um, the Emulator doesn’t emulate accelerometer data!

Yup.  If you downloaded my code from the bottom of this page, and wondered why the Z axis was reading a value of –1, it’s because the emulator assumes it is sitting on a flat surface.  It doesn’t have a way (out of the box) to emulate accelerometer data.  But there are some very smart people out there who HAVE found a way to make that happen.  I was really torn on the rest of this post.  Part of me wanted to write an example for each emulator solution, but there’s so many great ways to emulate accelerometer data, I figured it was better to let you know what’s possible than to just write code for each example.  Here’s a couple of suggestions of things you can try (each site offers code samples):

Reactive Extensions

Reactive Extensions is a framework that enables you to emulate accelerometer (as well as location, we’ll get to that on Day #13) data without a device.  You don’t really control that motion, however, as it just generates random data for you.  It’s simple to set up, and far more productive than stopping development just because you don’t have a phone yet. :)  There’s a great walkthrough on the MSDN website:  http://bit.ly/bdeaft

accelKit

This one is probably the coolest of the options available.  It leverages your webcam, and with augmented reality, allows you to move a printout of the phone like you would move one in real life.  I was absolutely blown away by how cool this is, for two reasons:

  1. It allows you to actually emulate your own motion.
  2. It uses AUGMENTED REALITY, people.  Just an amazing use of technology.

To see code samples, and download the additional libraries, head over here: http://bit.ly/9TfqaS

WiimoteLib

This library can be used for more than Windows Phone emulation, but it works amazingly well for our purposes as well.  The basic story is this: if you have a Nintendo Wii, you can use the controller (a Wiimote) to generate your accelerometer data.  Brian Peek is the developer that put together this little managed code library, and you can check out his site for the info you need to implement it!  http://bit.ly/aUdEEW

Windows Mobile Unified Sensor API

Yes, that reads “Windows Mobile.”  This was a way to interact with the accelerometer on certain types of Windows Mobile 6.x devices.  This post describes a simple way to leverage this technology for Windows Phone development as well.  They don’t seem to offer code samples, but it also seems pretty straightforward:  http://bit.ly/crHbW9

 

Download the Code

Remember that all of the above solutions should be temporary.  They are ways to “fake” accelerometer data until you can get your hands on a device, and that’s all.  There is no replacement for getting your code on a real device.  If you haven’t had a chance to do this yet, contact me, and I’ll see what I can do to get you in front of a phone, even if it’s only for a few hours.

download

22 thoughts on “31 Days of Windows Phone | Day #11: Accelerometer

  1. Nice post, Jeff! Thanks for including ways on how to test the accelerometer without a device. Counting down the time until I finally get my own device! 🙂

  2. Thanks for your posts. Real informative. Can you tell us that [b]HOW WE CAN CALCULATE FORCE BY USING THE INFORMATION OF ACCELEROMETER? [/b]OR is there any possible way of doing it?

  3. Ha! I love climbing up the local Bay Area hills and passing people with headphones. I'll say "Hi" as I pass them and it scares the crap out of them because they didn't hear me rolling up behind them.*-*

  4. Nice set of options for testing the accelerometer in the emulator.

    Too bad there isn't an option to use a WP7 phone to provide the accelerometer data!

  5. Bippittibop,

    Obviously, if you have a phone, you can debug your application on the device. Accelerometer, GPS, etc. They all work. Sorry if that wasn't mentioned in my article. At the time I wrote this, phones weren't even commercially available.

  6. Man cannot discover new oceans unless he has the courage to lose sight of the shore.

  7. Life is a process of becoming, a combination of states we have to go through. Where people fail is that they wish to elect a state and remain in it. This is a kind of death.

  8. Organized crime constitutes nothing less than a guerilla war against society.

  9. The American city should be a collection of communities where every member has a right to belong. It should be a place where every man feels safe on his streets and in the house of his friends. It should be a place where each individual's dignity and self-respect is strengthened by the respect and affection of his neighbors. It should be a place where each of us can find the satisfaciton and warmth which comes from being a member of the community of man. This is what man sought at the dawn of civilzation. It is what we seek today.

  10. Never read a book that is not a year old.

  11. Life consists not in holding good cards but in playing those you hold well.

  12. What is a man profited, if he shall gain the whole world, and lose his own soul I suppose this depends somewhat upon the size of the soul. I think there are cases where the trade would do.

  13. A man convinced of his own merit will accept misfortune as an honor, for thus can he persuade others, as well as himself, that he is a worthy target for the arrows of fate.

  14. Money There's nothing in the world so demoralizing as money.

  15. Death is not the worst rather, in vain To wish for death, and not to compass it.

  16. All theory, dear friend, is gray, but the golden tree of life springs ever green.

  17. It is not enough to have knowledge, one must also apply it. It is not enough to have wishes, one must also accomplish.

  18. Pingback: 31 Days of Mango | Day #1: The New Windows Phone Emulator Tools « Blankenblog

  19. Pingback: 31 Tage Mango | Tag #1: Die neuen Werkzeuge im Emulator | leitning.de

  20. Pingback: 31 Tage Mango | Tag #5: Das Gyroskop | leitning.de

  21. Pingback: La Liga Silverlight | Día 5: El giroscopio

  22. Pingback: Emulator Tools | TOPMING

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s