Mango Sample: Accelerometer
Mango Sample: Accelerometer
Join the DZone community and get the full member experience.Join For Free
Left? Right? Up? Down? Your application determines what is supported. Windows Phone supports multiple sensors providing information about the device’s orientation and location, including Compass, Gyroscope, and Accelerometer.
The Accelerometer tells your application if the user is tilting the phone and how much. Just reference Microsoft.Devices.Sensors and Microsoft.Xna.Framework.
Now, there are these few limitations to remember:
- Not while the screen is locked
- Not by a background agent
The Accelerometer simply requires you to instantiate it and start it. Let’s build a sample together. I will create a Rectangle and we’ll move it around the screen according to the Accelerometer. I will do it all in code-behind. Check this out:
Get the code here.
In the code above, see the TranslateTransform? This is the easiest way to move anything – simpler than using Canvas.Top/Left, Margin, or anything else. Also, the CurrentValueChanged event tells us when the UI should be updated. We’ll handle it like this:
In the code above, see the Dispatcher? The event fires on a thread that is not the UI thread. The Dispatcher will return us to the UI thread. Then we adjust the TranslateTransform’s X and Y properties within the containing ContentPanel boundaries.
When the X and the Y are reported by the Accelerometer, the value a positive (left) or negative (right) double value (between –1 and 0 and 1). The values represents the degree of tilt. This is easy to add the existing TranslateTransform X or Y. A multiple (like 5) moves faster.
Windows Phone includes the Combined Motion API. The Motion class handles the low-level sensor calculation and allows applications to easily obtain the device’s attitude (yaw, pitch, and roll), rotational acceleration, and linear acceleration both due to gravity and user movement.
Moment of honesty: the Combined Motion API is almost identical to the Accelerometer. Just switch “Accelerator” with “Motion” (it’s almost that easy). However, every time I try the emulator tells me the sensor is not present. Huh? So, rather than figure that out (I tried), this blog will skip right over the Combined Motion API, focusing on the Accelerometer.
Note: it’s worth noting, for what it is worth, that the Combined Motion API is the recommended API for Accelerometer data. You should prefer it for your application.
Accessing the Accelerometer data is easy. Adding tilt response to your application can make your program fun. Hopefully the code above will get you further along in using the Accelerometer data in your application.
Best of luck!
Opinions expressed by DZone contributors are their own.