An Overview of Windows 8 Sensor APIs
- Accelerometer
- Compass
- Geolocation
- Gyrometer
- Inclinometer
- Light Sensor
- Orientation Sensor
Touch input is not the only type of input that Windows 8 applications can process. Many Windows 8 devices contain special sensors that provide information like the physical orientation of the tablet or GPS coordinates. The Windows Runtime contains special APIs that allow you to tap into these sensors and build applications that respond to events like shaking the tablet, tilting the tablet, or providing contextual information based on the user’s location. This section contains a brief overview of the available sensor APIs.
If you have a device with one of these sensors present, you can download and run sample applications that use the sensors from Microsoft’s developer center. The following link will take you to a page to download a set of samples that includes a project for every sensor listed here (look for samples with Accelerometer, Gyrometer, Sensor, and Location in the title):
http://code.msdn.microsoft.com/windowsapps/Windows-8-Modern-Style-App-Samples
Accelerometer
The accelerometer provides information about the effect of gravity on the device across various axes. The API provides a current reading and generates an event when the reading changes. The event provides information about the acceleration in the X, Y, and Z planes. The code in Listing 4.4 demonstrates how to obtain a reading:
Listing 4.4: Reading Values from the Accelerometer
async private void ReadingChanged(object sender, AccelerometerReadingChangedEventArgs e) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { AccelerometerReading reading = e.Reading; ScenarioOutput_X.Text = String.Format("{0,5:0.00}", reading.AccelerationX); ScenarioOutput_Y.Text = String.Format("{0,5:0.00}", reading.AccelerationY); ScenarioOutput_Z.Text = String.Format("{0,5:0.00}", reading.AccelerationZ); }); }
You can learn more about the accelerometer and run a sample application by reading the MSDN documentation found at http://msdn.microsoft.com/en-us/library/windows/apps/windows.devices.sensors.accelerometer.aspx.