Jerry Nixon @Work: WP7 Sample: An Accelerator-based App in 5 Minutes

Jerry Nixon on Windows

Tuesday, February 14, 2012

WP7 Sample: An Accelerator-based App in 5 Minutes

As I have discussed in previous posts, there are lots of great sensors at the disposal of the Windows Phone application developer. One of them is the Accelerometer. The accelerometer measures the tilt of the device in both the X axis and Y axis.

You can read my previous article about the Accelerometer in more detail.

This can be quite useful for game scenarios. It can also be useful in productivity applications where the developer is using additional forms of user interaction to offer greater usability or innovation.

Let’s Build Something!

In the following video, I build a very simple application that leverages the Accelerometer to move a circle around on the screen. Hopefully this simple sample is enough to get you started to leverage the Accelerometer in your application.

Unable to display content. Adobe Flash is required.

In the previous video, I left out all the frills. Using the Accelerometer really is as simple as a few lines of code. Just be sure and reference XNA and Microsoft.Devices.Sensors to access the capabilities.

What I don’t do is leverage the new Motion API that unifies multiple sensors to provide information about orientation and motion. This sample is the bare bones “how to use accelerometer” but it is worth saying that your application might benefit most from the Motion API

The Code

I really love how little code is necessary to accomplish a complex task.

image

In the code above, we need only Start() the Accelerometer for it to begin working. When the sensor detects a tilt, it raises the CurrentValueChanged event. It is there we handle the delta provided from the event (the amount changed since the last event was raised).

The only thing to remember is that we need to return from the Accelerometer’s thread to the UI thread. I discuss this also here. But, in short, we accomplish this by executing the logic in the handler inside the Dispatcher for the application.

Conclusion

Windows Phone developers don’t just have a bevy of sensors in their arsenal, they have XAML. And you would be remiss to dismiss XAML as a simple declarative UI technology (although it is that). XAML in the Silverlight Engine gives developers tools and controls to perform many complex and amazing tasks with ease. Many of these tasks, including the use of TranslateTransform (in this video) can take benefit of the local hardware.

Ready to tilt?

Best of luck!