Monday, January 28, 2013

How to use the Accelerometer in Windows 8 C#/XAML Applications

How to use the Accelerometer in Windows 8 C#/XAML Applications:
This post is part of a mulit-part posting series on how to use some of the onboard device sensors in Windows 8 applications.  Other posts are:
Most tablets and laptops these days have an array of sensors onboard the device that developers can use and take advantage of. One of the sensors which is on most tables and laptops is the Accelerometer Sensor.  The Accelerometer sensor can be used to get a acceleration force of the device on the x y and z axis, or basically measure how fast it is moving in any given direction.  With the Accelerometer you could build interesting augmented reality applications which react to the forces of the device.  In this post we are going to take a look at how to use the Accelerometer Sensor from within your C#/XAML Windows 8 application.
How to get access to the Inclinometer
private Sensor.Accelerometer _accelerometer;
private void SetupSensor()
{
    _accelerometer = Sensor.Accelerometer.GetDefault();

    if (_accelerometer == null)
    {
        // tell user they don't have an Accelerometer
    }
}

In the above code what we are doing is making the call to get the Default sensor, this is the sensor on the device.  If there is NO sensor on the users device it will return a NULL instance which is why we are checking for null.  Make sure you do the same in your code

Register to receive event updates when the Accelerometer values change

private void SetupEventing(bool enableEventing)
{
    if( enableEventing)
    {
        _accelerometer.ReadingChanged += AccelerometerOnReadingChanged;
        CurrentReadingStyle = 'Eventing';
    }
    else
    {
        _accelerometer.ReadingChanged -= AccelerometerOnReadingChanged;
        CurrentReadingStyle = 'Stopped';
    }
}

In the above I am either registering for an event or unregistering.  The event is what will give us the updated values as they change based on the movement of the users device.

Doing something useful with the sensor readings

private CoreDispatcher _dispatcher;

private async void AccelerometerOnReadingChanged(Sensor.Accelerometer sender, Sensor.AccelerometerReadingChangedEventArgs args)
{
    await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, 
        () =>
            {
                XAcceleration = args.Reading.AccelerationX;
                YAcceleration = args.Reading.AccelerationY;
                ZAcceleration = args.Reading.AccelerationZ;

                SetupNewLocation();
            });
}

In the above I am doing 2 things of note:

  1. I am using a CoreDispatcher (you can get this from Window.Current.Dispatcher) in order to message the results back onto the UI thread.  If you do not need to message back to the UI thread you will NOT need this
  2. I am getting the current reading for each axis via the .Reading property of the event argument.  It is here you could do something useful with the reading.

Apart from being able to get the changed events for the Accelerometer you can also detect if the device has been shaking by listing to those events as well.

Register to receive event updates when the Accelerometer shaek change

private void SetupShaken(bool enableShaking)
{
    if ( enableShaking )
    {
        _accelerometer.Shaken += AccelerometerOnShaken;
        ShakeCount = 0;
        CurrentReadingStyle = "Shaking";
    }
    else
    {
        _accelerometer.Shaken -= AccelerometerOnShaken;
        CurrentReadingStyle = "Stopped";
    }
}

In the above code I am wiring an event to tell me each time the Accelerometer notices the device has been shaken.

Handle the Shaken Event and do something.

private async void AccelerometerOnShaken(Sensor.Accelerometer sender, Sensor.AccelerometerShakenEventArgs args)
{
    await _dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                () =>
                                    {
                                        ShakeCount = ShakeCount + 1;
                                    });
}

In the above code I have received the Shaken Event and I am simply updating a counter.  Of course in a real world app you would want to do something a bit more exciting, but this gets the point across.

As you can see working with the Accelerometer sensor is not too hard and can lead to some pretty useful features in your application.

Till next time,


DIGITAL JUICE

No comments:

Post a Comment

Thank's!