Home Archive Contact Subscribe Twitter LinkedIn
>
31 Days of Windows Phone | Day #11: Accelerometer
By Jeff Blankenburg11. October 2010 02:00
This post is Day #11 in a series called the 31 Days of Windows Phone.
Yesterday, we talked about the software-based keyboard on Windows Phone. Today, we’re going to talk about the hardware-based accelerometer, and how we can take advantage of the information it provides.
What is an accelerometer?
For lack of a better definition, an accelerometer is a sensor in the Windows Phone devices that measures the acceleration on 3 axes (X, Y, Z), relative to freefall. In addition to a timestamp, the values are expressed in G-forces (1G = 9.81 m/s2). What this means is that if the phone is lying face-up on a perfectly flat surface, the Z axis would read –1.0, and the other two axes would read 0. Here’s a quick illustration showing the different values (thanks to WindowsTeamBlog for the image):
How do I get values from the WP7 Accelerometer?
Thankfully, this is pretty simple. The one major complication is that we have some thread management to handle, but it’s really simple stuff. Here’s what we need to do:
Instantiate a new Accelerometer object.
Create a new ReadingChanged() event handler to monitor the changes in data.
Pass the results of that event back to our page’s thread (the event fires on a different thread).
Use the data values in our application.
Here’s the entirety of my MainPage.xaml.cs file for this example. You’ll see that I have created three TextBlocks (XText, YText, and ZText) on my MainPage.xaml file, so that I can write the values to the screen. Also notice that I had to add a new reference to Microsoft.Devices.Sensors to get access to the Accelerometer.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Devices.Sensors;
namespace Day11_Accelerometer
{
public partial class MainPage : PhoneApplicationPage
{
Accelerometer acc = new Accelerometer();
// Constructor
public MainPage()
{
InitializeComponent();
acc.ReadingChanged += new EventHandler(acc_ReadingChanged);
acc.Start();
}
void acc_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
{
Deployment.Current.Dispatcher.BeginInvoke(() => ThreadSafeAccelerometerChanged(e));
}
void ThreadSafeAccelerometerChanged(AccelerometerReadingEventArgs e)
{
XText.Text = e.X.ToString("0.000");
YText.Text = e.Y.ToString("0.000");
ZText.Text = e.Z.ToString("0.000");
}
}
}
额,模拟器不能够使加速器工作
的确。如果你下载我的代码并且诧异为什么z轴值为-1,这是因为模拟器认为他在一个水平面上滑动。没有方法来模拟加速器数据。但是一些聪明的家伙发现了解决办法。我正在解密,我的确想写所有的方法,但是有太多的方法,我觉得最好让你知道原理胜过只是写代码。 下面是一些建议,你可以一试: