1. 引人传感器类库
using Microsoft.Devices.Sensors
2.通过Accelerometer.IsSupported判断当前设备是否支持加速度传感器,如果返回false则表示设备不支持加速度感应器。
f (Accelerometer.IsSupported)
{
// lblAccelerometerStatus.Text = "此设备支持加速度传感器";
}
else
{
// lblAccelerometerStatus.Text = "此设备不支持加速度传感器";
}
3.打开加速度设备,设置监听获得,x,y,z轴对应的加速度值
private Accelerometer _accelerometer;
private void btnStart_Click(object sender, RoutedEventArgs e)
{
if (_accelerometer == null)
{
// 实例化 Accelerometer,注册相关事件
_accelerometer = new Accelerometer();
_accelerometer.TimeBetweenUpdates = TimeSpan.FromMilliseconds(1);
_accelerometer.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<AccelerometerReading>>(_accelerometer_CurrentValueChanged);
lblTimeBetweenUpdates.Text = "TimeBetweenUpdates 设置为 1 毫秒,实际为 " + _accelerometer.TimeBetweenUpdates.TotalMilliseconds.ToString() + " 毫秒";
}
try
{
// 打开加速度传感器
_accelerometer.Start();
lblAccelerometerStatus.Text = "加速度传感器已打开";
} catch (Exception ex)
{
lblAccelerometerStatus.Text = "加速度传感器已打开失败";
MessageBox.Show(ex.ToString());
}
}
void _accelerometer_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
{
// 注:此方法是在后台线程运行的,所以需要更新 UI 的话注意要调用 UI 线程
Dispatcher.BeginInvoke(() => UpdateUI(e.SensorReading));
}
// 更新 UI
private void UpdateUI(AccelerometerReading accelerometerReading)
{
Vector3 acceleration = accelerometerReading.Acceleration;
// 输出 X Y Z 的值
lblMsg.Text = "acceleration.X: " + acceleration.X.ToString("0.0");
lblMsg.Text += Environment.NewLine;
lblMsg.Text += "acceleration.Y: " + acceleration.Y.ToString("0.0");
lblMsg.Text += Environment.NewLine;
lblMsg.Text += "acceleration.Z: " + acceleration.Z.ToString("0.0");
}
4.关闭监听
if (_accelerometer != null)
{
// 关闭加速度传感器
_accelerometer.Stop();
lblAccelerometerStatus.Text = "加速度传感器已关闭";
}