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:
- Light Sensor
- Gyrometer Sensor (this post)
- Inclinometer Sensor (future post)
- Accelerometer Sensor (future post)
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 Gyrometer Sensor. The Gyrometer sensor can be used to get a angular velocity of the device on the X, Y and Z axis. In this post we are going to take a look at how to use the Gyrometer Sensor from within your C#/XAML Windows 8 application.
How to get access to the Gyrometer
private Windows.Devices.Sensors.Gyrometer _gyrometer;
private void SetupSensor()
{
_gyrometer = Windows.Devices.Sensors.Gyrometer.GetDefault();
if (_gyrometer == null)
{
// there is no grometer on this device.....
}
}
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 Gyrometer values change
private void SetupEventing(bool enableEventing)
{
if (enableEventing)
{
_gyrometer.ReadingChanged += GyrometerOnReadingChanged;
CurrentReadingStyle = "Eventing";
}
else
{
_gyrometer.ReadingChanged -= GyrometerOnReadingChanged;
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 GyrometerOnReadingChanged(Sensor.Gyrometer sender, Sensor.GyrometerReadingChangedEventArgs args)
{
await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
XAxisReading = args.Reading.AngularVelocityX;
YAxisReading = args.Reading.AngularVelocityY;
ZAxisReading = args.Reading.AngularVelocityZ;
});
}
In the above I am doing 2 things of note:
- 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
- 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.
As you can see working with the Gyrometer sensor is not too hard and can lead to some pretty useful features in your application.
Till next time,
Posted
01-21-2013 5:55 PM
by
Derik Whittaker