日期:2014-05-17  浏览次数:20880 次

windows phone 7 重力感应控制wifi小车

建立好wifi并能通过socket发送控制指令之后,就想用手机的重力感应来控制小车行驶方向。感觉很酷哈~~~

其实获取重力感应信息的代码比较简单,就几行:

 

引用

using Microsoft.Devices.Sensors;

定义

private Accelerometer acc;

//下面几个变量是我程序里要用的

        private int cpow = 0;

        private double oldy = 0;

        private bool isSendRight = false;
        private bool isSendLeft = false;
        private bool isSendCenter = false;
        private string movetype = string.Empty;

然后在formload事件里加上

            acc = new Accelerometer();
            acc.CurrentValueChanged += new EventHandler<SensorReadingEventArgs<AccelerometerReading>>(acc_CurrentValueChanged);
            acc.Start();

这样程序就能实时拿到重力感应数据了,然后为事件写几行代码:

 void acc_CurrentValueChanged(object sender, SensorReadingEventArgs<AccelerometerReading> e)
        {
            //3轴加速度值
            Vector3 vt = new Vector3();
            vt = e.SensorReading.Acceleration;

            //获取Y坐标值,即手机横放之后左右两边方向的值
            double y = vt.Y * 100;
            //允许+ -10范围内的晃动
            if (y <= -10 || y >= 10)
            {
                //计算偏移量转化的速度值
                cpow = (int)(oldy - Math.Abs(y));
                //左偏移
                if (y < 0 && isSendLeft == false)
                {
                    SendData("moto:4");
                    isSendLeft = true;
                }
                //右偏移
                if (y > 0 && isSendRight == false)
                {
                    SendData("moto:3");
                    isSendRight = true;
                }
                isSendCenter = false;
            }