31 Days of Windows 8 | Day #25: Accelerometer

This article is Day #25 in a series called 31 Days of Windows 8.  Each of the articles in this series will be published for both HTML5/JS and XAML/C#. You can find additional resources, downloads, and source code on our website.

advertisementsample4

Today, we’re looking at yet another sensor available in Windows 8 devices, the Accelerometer.  It measure the acceleration of the device on 3 axes, X, Y, and Z.

The X axis runs horizontally across the device.  The Y axis runs vertically across the device.  The Z axis runs immediately through the device, from front to back.  Here’s an image to help illustrate, using a Windows Phone as the example (courtesy of http://www.andybeaulieu.com/):

25-Accelerometer

In simpler terms, we’re measuring the g-forces applied to those three axes.  Because of this, when we lay a Windows 8 tablet flat on a table, we get a Z axis value of –1, because there is one “g” (one unit of gravity) exerting itself on the negative size of the Z axis.  In the same way, if we propped our device up (similar to the phone in the photo) so that the bottom of the device is sitting on the table, we would get a Y axis value of –1.

So how do we gather these values?  Very similarly to how we have interacted with the past few sensors.  We create an Accelerometer object, we add an event handler, and we read the data when it changes.  Here’s my entire MainPage.xaml.cs file:

using System;
using Windows.Devices.Sensors;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
 
namespace Day25_Accerometer
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }
 
        Accelerometer accelerometer;
        int shakes;
 
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            accelerometer = Accelerometer.GetDefault();
            if (accelerometer != null)
            {
                accelerometer.ReadingChanged += accelerometer_ReadingChanged;
                accelerometer.Shaken += accelerometer_Shaken;
                Data.Visibility = Visibility.Visible;
            }
            else
            {
                NoSensorMessage.Visibility = Visibility.Visible;
            }
        }
 
        async void accelerometer_ReadingChanged(Accelerometer sender, AccelerometerReadingChangedEventArgs args)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                XValue.Text = args.Reading.AccelerationX.ToString();
                YValue.Text = args.Reading.AccelerationY.ToString();
                ZValue.Text = args.Reading.AccelerationZ.ToString();
                TimeStamp.Text = args.Reading.Timestamp.ToString();
            });
        }
 
        async void accelerometer_Shaken(Accelerometer sender, AccelerometerShakenEventArgs args)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                shakes++;
                ShakeCount.Text = shakes.ToString();
            });
        }
    }
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

If you have been following along with this series, this should look really familiar.  If you haven’t, you can see that we’re using the ReadingChanged event handler to grab our data values from the Accelerometer object, and then using the Dispatcher to write those values to our UI thread.

The one major difference you should notice is the new Shaken event handler.  Some accelerometers support this function, and others don’t, but we just don’t get any data when it’s not supported (it’s basically just a meta-calculation that approximates when the user’s device has been shaken similarly to how you might shake an Etch-A-Sketch to erase the screen.)  If you’re going to use this event, be sure that the user is using a device that supports it, like the Microsoft Surface.

You can certainly use the X, Y, and Z values to determine a shake on your own, so the Shaken event will likely not be of huge value to you until it is more widely supported.  By using these values, however, you can do some pretty impressive math.  Think of games like Labyrinth, and how you can use the angle of the device to determine where the objects on the screen should move.  I think there are tons of applications for this, and I’m looking forward to seeing what you create.

Summary

Today we took a look at the Accelerometer sensor, and how we can use it to grab data about the orientation and acceleration of the device on three different axis directions.

If you would like to download the sample application that uses the code from this article, click the icon below:

downloadXAML

Tomorrow, we’ll continue diving into sensors with the Inclinometer.  It allows us to measure the angle of incline for a Windows 8 device on the same three axes.  See you then!

downloadTheTools

2 thoughts on “31 Days of Windows 8 | Day #25: Accelerometer

  1. Pingback: The Daily Six Pack: November 26, 2012 | Dirk Strauss

  2. Pingback: 31 Days of Windows 8 | Day #25: Accelerometer

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