Example #1
0
 //robcamer - add Accelerometer reading
 void accelerometer_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
 {
     CurrentAccelerometerState.X         = e.X;
     CurrentAccelerometerState.Y         = e.Y;
     CurrentAccelerometerState.Y         = e.Z;
     CurrentAccelerometerState.Timestamp = e.Timestamp;
 }
 private void Acc_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
 {
     lblValores.Dispatcher.BeginInvoke(delegate()
     {
         lblValores.Text = String.Format("X = {0:F2}, \nY = {1:F2}, \nZ = {2:F2}", e.X, e.Y, e.Z);
     });
 }
Example #3
0
        void gSensor_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {
            LogoVelocity.X += (float)e.X;
            LogoVelocity.Y += -(float)e.Y;

            LogoPosition += LogoVelocity;
        }
Example #4
0
        private void MyReadingChanged(AccelerometerReadingEventArgs e)
        {
            double distanceToTravel   = 2;
            double accelerationFactor = Math.Abs(e.Z) == 0 ? 0.1 : Math.Abs(e.Z);
            double ballX = (double)ball.GetValue(Canvas.LeftProperty) + distanceToTravel * e.X / accelerationFactor;
            double ballY = (double)ball.GetValue(Canvas.TopProperty) - distanceToTravel * e.Y / accelerationFactor;

            if (ballX < 0)
            {
                ballX = 0;
            }
            else if (ballX > ContentGrid.Width)
            {
                ballX = ContentGrid.Width;
            }

            if (ballY < 0)
            {
                ballY = 0;
            }
            else if (ballY > ContentGrid.Height)
            {
                ballY = ContentGrid.Height;
            }

            ball.SetValue(Canvas.LeftProperty, ballX);
            ball.SetValue(Canvas.TopProperty, ballY);
        }
 public void AccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs e)
 {
     //改变捕鱼网的位置
     logoVelocity.X += (float)e.X;
     logoVelocity.Y += -(float)e.Y;
     logoPosition += logoVelocity;
 }
        public PongGameScreen()
        {
            TransitionOnTime  = TimeSpan.FromSeconds(0.0);
            TransitionOffTime = TimeSpan.FromSeconds(0.0);
            screenLeftBound   = 0;
            screenRightBound  = 480;
            screenTopBound    = 0;
            screenBottomBound = 800;

            Accelerometer = new Accelerometer();
            if (Accelerometer.State == SensorState.Ready)
            {
                Accelerometer.ReadingChanged += (s, e) =>
                {
                    accelState = e;
                };
                Accelerometer.Start();
            }
            lastAccelInput      = 0f;
            bottomPaddleTouch   = new TouchLocation();
            bottomPaddleTouchId = -1;
            lastTouchInput      = new List <TouchLocation>();
            lastKeyInput        = new List <Keys>();

            bottomPaddle = new DefaultPaddle();
            topPaddle    = new DefaultPaddle();
        }
        public GameplayScreen()
        {
            random = new Random();

            worldBounds = new Rectangle(0, 0, (int)screenWidth, (int)screenHeight);

            gameOver = true;

            TransitionOnTime  = TimeSpan.FromSeconds(0.0);
            TransitionOffTime = TimeSpan.FromSeconds(0.0);

            player        = new Player();
            playerBullets = new List <Bullet>();

            aliens       = new List <Alien>();
            alienBullets = new List <Bullet>();

            Accelerometer = new Accelerometer();
            if (Accelerometer.State == SensorState.Ready)
            {
                Accelerometer.ReadingChanged += (s, e) =>
                {
                    accelState = e;
                };
                Accelerometer.Start();
            }
        }
Example #8
0
 void OnAccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs args)
 {
     lock (accelerometerVectorLock)
     {
         accelerometerVector = new Vector3((float)args.X, (float)args.Y, (float)args.Z);
     }
 }
Example #9
0
 public void AccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs e)
 {
     _Accel = (float)e.X;
     //_Accel.X = (float)e.X;
     //_Accel.Y = (float)e.Y;
     //_Accel.Z = (float)e.Z;
 }
Example #10
0
        void accel_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {
            Dispatcher.BeginInvoke(new Action(() =>
            {
                previousY = currentY;
                currentY  = e.Y;

                if (e.Y > .7 || e.Y < -.7)
                {
                    if (e.Y > .7 && !isTurnDirty)
                    {
                        isTurnDirty = true;
                        Turn(1);
                    }
                    else if (e.Y < -.7 && !isTurnDirty)
                    {
                        isTurnDirty = true;
                        Turn(-1);
                    }
                }
                else
                {
                    isTurnDirty = false;
                }
            }));
        }
Example #11
0
            void UpdateBallAcceleration(AccelerometerReadingEventArgs e)
            {
                // by default, XNA App works in landscape mode, while
                // accelerometer assumes portrait.
                //    XYZ ranges are betwen -2 and +2
                // Gravitatoin pull is -1
                //
                const float kAccelerationScale = 0.5f;
                float       x = kAccelerationScale * (float)e.X;
                float       y = kAccelerationScale * (float)e.Y;

                mAccValues.Z = kAccelerationScale * (float)e.Z;

                switch (mCurrentOrientation)
                {
                case DisplayOrientation.Portrait:
                    mAccValues.X = x;
                    mAccValues.Y = -y;
                    break;

                case DisplayOrientation.LandscapeLeft:
                    mAccValues.X = -y;
                    mAccValues.Y = -x;
                    break;

                case DisplayOrientation.LandscapeRight:
                    mAccValues.X = y;
                    mAccValues.Y = x;
                    break;
                }
            }
Example #12
0
 /*
  *
  * Чтение и запись значений акселерометра в переменную
  *
  */
 private void my_readingChanged(AccelerometerReadingEventArgs e)
 {
     if (myAcs != null)
     {
         bA = new bufAcs((float)e.X, (float)e.Y, (float)e.Z);
     }
 }
        private void Acc_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {
            bolinha.Dispatcher.BeginInvoke(delegate()
            {
                if (e.X > 0)
                {
                    valorX += 1;
                    Canvas.SetLeft(bolinha, valorX);
                }
                else if (e.X < 0)
                {
                    valorX -= 1;
                    Canvas.SetLeft(bolinha, valorX);
                }



                if (e.Y > 0)
                {
                    valorY += 1;
                    Canvas.SetTop(bolinha, valorY);
                }
                else if (e.Y < 0)
                {
                    valorY -= 1;
                    Canvas.SetTop(bolinha, valorY);
                }
            });
        }
Example #14
0
 void acc_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
 {
     Dispatcher.BeginInvoke(() =>
     {
         this.Proj.RotationX = e.Z * 90;
         this.Proj.RotationY = e.X * -90;
     });
 }
Example #15
0
 void OnAccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs args)
 {
     lock (accelerationLock)
     {
         acceleration = 0.5f * oldAcceleration +
                        0.5f * new Vector3((float)args.X, (float)args.Y, (float)args.Z);
         oldAcceleration = acceleration;
     }
 }
Example #16
0
 // Accelerometer callback.
 private void OnAccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs eventArgs)
 {
   // Store the accelerometer value in our variable to be used on the next Update. This callback
   // can come from another thread!
   lock (_syncRoot)
   {
     _accelerometerCallbackValue = new Vector3((float)eventArgs.X, (float)eventArgs.Y, (float)eventArgs.Z);
   }
 }
        private void OnAccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs args)
        {
            Double Magnitude = Math.Sqrt(args.X * args.X + args.Y * args.Y + args.Z * args.Z);

            if (Magnitude >= 1.5)
            {
                mMagnitudeList.Add(new AccData(args.X, args.Y, args.Z, Magnitude, args.Timestamp));
            }
        }
Example #18
0
        protected void accelerometer_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {
            if (accelerometerIsDisabled)
            {
                return;
            }

            this.myPlayer.ChangeBarSpeed(e.Y);
        }
 private string ReadingValue(AccelerometerReadingEventArgs args)
 {
     string AccelerationVector = "<null>";
     if (null != args)
     {
         AccelerationVector = String.Format("X = {0}; Y = {1}; Z = {2}; TS = {3}", args.X, args.Y, args.Z, args.Timestamp);
     }
     return AccelerationVector;
 }
Example #20
0
 private void ProcessAccelerometerReading(AccelerometerReadingEventArgs e)
 {
     txtTime.Text  = e.Timestamp.ToString();
     txtX.Text     = e.X.ToString();
     txtY.Text     = e.Y.ToString();
     txtZ.Text     = e.Z.ToString();
     txtPitch.Text = RadianToDegree((Math.Atan(e.X / Math.Sqrt(Math.Pow(e.Y, 2) + Math.Pow(e.Z, 2))))).ToString();
     txtRoll.Text  = RadianToDegree((Math.Atan(e.Y / Math.Sqrt(Math.Pow(e.X, 2) + Math.Pow(e.Z, 2))))).ToString();
     txtYaw.Text   = RadianToDegree((Math.Atan(Math.Sqrt(Math.Pow(e.X, 2) + Math.Pow(e.Y, 2)) / e.Z))).ToString();
 }
Example #21
0
 void UpdateAccData(AccelerometerReadingEventArgs e)
 {
     txtXvalue.Text = e.X.ToString("0.000") + "g";
     txtYvalue.Text = e.Y.ToString("0.000") + "g";
     txtZvalue.Text = e.Z.ToString("0.000") + "g";
     if (txtZvalue.Text.Equals("NeuN"))
     {
         txtZvalue.Text = "No disponible";
     }
 }
Example #22
0
 /// <summary>
 /// Method for handling the ReadingChanged event on the UI thread.
 /// This sample just displays the reading value.
 /// </summary>
 /// <param name="e"></param>
 void MyReadingChanged(AccelerometerReadingEventArgs e)
 {
     if (accelerometer != null)
     {
         statusTextBlock.Text = accelerometer.State.ToString();
         XTextBlock.Text = e.X.ToString("0.00");
         YTextBlock.Text = e.Y.ToString("0.00");
         ZTextBlock.Text = e.Z.ToString("0.00");
     }
 }
Example #23
0
 /// <summary>
 /// Method for handling the ReadingChanged event on the UI thread.
 /// This sample just displays the reading value.
 /// </summary>
 /// <param name="e"></param>
 void MyReadingChanged(AccelerometerReadingEventArgs e)
 {
     if (accelerometer != null)
     {
         statusTextBlock.Text = accelerometer.State.ToString();
         XTextBlock.Text      = e.X.ToString("0.00");
         YTextBlock.Text      = e.Y.ToString("0.00");
         ZTextBlock.Text      = e.Z.ToString("0.00");
     }
 }
Example #24
0
        void accelerometer_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {
            //
            AccelerometerTemp.X = (float)e.X;
            AccelerometerTemp.Y = (float)e.Y;
            AccelerometerTemp.Z = (float)e.Z;

            AccelerometerHelper.Current3DAcceleration = AccelerometerTemp;
            AccelerometerHelper.CurrentTimeStamp      = e.Timestamp;
        }
        private static bool CheckForShake(AccelerometerReadingEventArgs last, AccelerometerReadingEventArgs current,
                                            double threshold)
        {
            double deltaX = Math.Abs((last.X - current.X));
            double deltaY = Math.Abs((last.Y - current.Y));
            double deltaZ = Math.Abs((last.Z - current.Z));

            return (deltaX > threshold && deltaY > threshold) ||
                    (deltaX > threshold && deltaZ > threshold) ||
                    (deltaY > threshold && deltaZ > threshold);
        }
Example #26
0
 public virtual void AccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs args)
 {
     // this event fires on a different thread than the game loop, and the
     // class is composed of multiple non-atomic data members, so even though
     // there's only one writer, we don't want to update the value while it's
     // being read elsewhere.
     lock (accelerometerLockObject)
     {
         LastState = State;
         State     = new Vector3((float)args.X, (float)args.Y, (float)args.Z);
     }
 }
Example #27
0
        private void HandleSensorReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {
            if (this.ReadingChanged != null) {
                var args = new AccelerometerEventArgs() {
                    X = e.X,
                    Y = e.Y,
                    Z = e.Z
                };

                this.ReadingChanged(this, args);
            }
        }
 public virtual void AccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs args)
 {
     // this event fires on a different thread than the game loop, and the 
     // class is composed of multiple non-atomic data members, so even though
     // there's only one writer, we don't want to update the value while it's
     // being read elsewhere.
     lock (accelerometerLockObject)
     {
         LastState = State;
         State = new Vector3((float)args.X, (float)args.Y, (float)args.Z);
     }
 }
Example #29
0
        /// <summary>
        /// Check if the phone is shaking.
        /// </summary>
        /// <param name="lastValue">The last value that was read from the accelerometer.</param>
        /// <param name="currentValue">The current value that was read from the accelerometer.</param>
        /// <param name="threshold">The threshold value for the difference in one of the axes that constitutes as
        /// the phone being shaken.</param>
        /// <returns>True if the phone has been shaken and false otherwise.</returns>
        private static bool CheckForShake(Vector3 lastValue,
                                          AccelerometerReadingEventArgs currentValue, double threshold)
        {
            // Calculate the difference between the last two accelerometer readings
            double deltaX = Math.Abs((double)(lastValue.X - currentValue.X));
            double deltaY = Math.Abs((double)(lastValue.Y - currentValue.Y));
            double deltaZ = Math.Abs((double)(lastValue.Z - currentValue.Z));

            // If the difference is bigger than the threshold, the phone was shaken
            return((deltaX > threshold && deltaY > threshold) ||
                   (deltaX > threshold && deltaZ > threshold) ||
                   (deltaY > threshold && deltaZ > threshold));
        }
Example #30
0
        private void accelerometer_ReadingChanged(
            object sender, AccelerometerReadingEventArgs e)
        {
            currentReading.X         = e.X;
            currentReading.Y         = e.Y;
            currentReading.Z         = e.Z;
            currentReading.Timestamp = e.Timestamp;

#if DEBUG
            System.Diagnostics.Debug.WriteLine("X: " + e.X);
            System.Diagnostics.Debug.WriteLine("Y: " + e.Y);
            System.Diagnostics.Debug.WriteLine("Z: " + e.Z);
#endif
        }
Example #31
0
        // Callback when new actual sensor readings are available.
        private void OnReadingChanged(object sender, AccelerometerReadingEventArgs args)
        {
            RawAcceleration  = new Vector3((float)args.X, (float)args.Y, (float)args.Z);
            RawAcceleration -= SensorError;

            float dt = (float)args.Timestamp.Subtract(LastSensorTime).TotalSeconds;

            LastSensorTime = args.Timestamp;
            dt             = MathHelper.Clamp(dt, 0.0f, 1.0f);

            float p = (float)Math.Exp(-dt / Smoothing);

            SmoothAcceleration = Vector3.Lerp(RawAcceleration, SmoothAcceleration, p);
        }
Example #32
0
        public GameplayScreen()
        {
            TransitionOnTime = TimeSpan.FromSeconds(0.0);
            TransitionOffTime = TimeSpan.FromSeconds(0.0);

            Accelerometer = new Accelerometer();
            if (Accelerometer.State == SensorState.Ready)
            {
                Accelerometer.ReadingChanged += (s, e) =>
                {
                    accelState = e;
                };
                Accelerometer.Start();
            }
        }
Example #33
0
 void acc_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
 {
     // throw new NotImplementedException();
     Dispatcher.BeginInvoke(() =>
     {
         if (this.Orientation == PageOrientation.LandscapeLeft)
         {
             dirRotation -= e.Y;
             angle       -= e.Y;
         }
         else
         {
             dirRotation += e.Y;
             angle       += e.Y;
         }
     });
 }
Example #34
0
        public void AccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {
            if (driveEnable)
            {

                accelReading.X = (float)e.X * 100;
                accelReading.Y = (float)e.Y * 100;
                accelReading.Z = (float)e.Z * 100;
                Dispatcher.BeginInvoke(() =>
                speedValue.Text = this.accelReading.Z.ToString());
                Dispatcher.BeginInvoke(() =>
                turnValue.Text = this.accelReading.Y.ToString());

                client.Send("relay #" + accelReading.Z.ToString() + "," + accelReading.Y.ToString());
                client.Receive();
            }
        }
 /// <summary>
 /// A callback function for Accelerometer to notify that the sensor reading has changed.
 /// This method reads the acceleration along the x axis, then scales and clamp it between
 /// 0 and -30.
 /// </summary>
 /// <param name="sender">The caller of this function</param>
 /// <param name="e">the parameter wich holds the data of the sensor</param>
 private void sensor_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
 {
     lock (threadLock)
     {
         if (e.X < -0.6)
         {
             xRot = -30.0f;
             return;
         }
         if (e.X > 0)
         {
             xRot = 0;
             return;
         }
         xRot = (float)e.X / 0.6f * 30.0f;
     }
 }
 /// <summary>
 /// A callback function for Accelerometer to notify that the sensor reading has changed.
 /// This method reads the acceleration along the x axis, then scales and clamp it between
 /// 0 and -30.
 /// </summary>
 /// <param name="sender">The caller of this function</param>
 /// <param name="e">the parameter wich holds the data of the sensor</param>
 private void sensor_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
 {
     lock (threadLock)
     {
         if (e.X < -0.6)
         {
             xRot = -30.0f;
             return;
         }
         if (e.X > 0)
         {
             xRot = 0;
             return;
         }
         xRot = (float)e.X / 0.6f * 30.0f;
     }
 }
Example #37
0
 void accelSensor_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
 {
     if (connectionMgr.IsStarted)
     {
         var steer = -2 * (float)e.Y;
         if (steer > 1)
         {
             steer = 1;
         }
         if (steer < -1)
         {
             steer = -1;
         }
         input.steer = steer;
         connectionMgr.SendContent(input);
     }
 }
Example #38
0
        private void AccelerometerChanged(AccelerometerReadingEventArgs e)
        {
            var t = e.Timestamp.DateTime;

            if ((t - ShakeTimePivot).TotalMilliseconds > ShakeDelay)
            {
                if (e.X > ShakeThresholdX)
                {
                    MoveFoot();
                    ShakeTimePivot = DateTime.Now;
                }
                else if (e.Z > ShakeThresholdZ)
                {
                    BowHead();
                    ShakeTimePivot = DateTime.Now;
                }
            }
        }
        void _accelerometer_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {
            if (_estadoJogo == EstadoJogo.Fim || _estadoJogo == EstadoJogo.Pause)
                return;

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                this.ballPosition.X += e.X * 6;
                if (this.ballPosition.X >= 480 - ball.Width)
                {
                    this.ballPosition.X = 480 - ball.Width;
                }
                else if (this.ballPosition.X <= 0)
                {
                    this.ballPosition.X = 0;
                }
            });
        }
        private void OnAccelData(object sender, AccelerometerReadingEventArgs args)
        {
            // Raw un-smoothed accel from sensor
            RawAcceleration = new Vector3((float)args.X, (float)args.Y, (float)args.Z);

            // Empirically determined error in accelerometer readings. It seems to be off by a constant offset.
            Vector3 SensorError = new Vector3(-0.09f, -0.02f, 0.04f);

            // reduce the data by an allocated error factor
            RawAcceleration -= SensorError;

            float dt = (float)args.Timestamp.Subtract(LastSensorTime).TotalSeconds;

            LastSensorTime = args.Timestamp;
            dt             = MathHelper.Clamp(dt, 0.0f, 1.0f);

            float p = (float)Math.Exp(-dt / Smoothing);

            SmoothedAcceleration = Vector3.Lerp(RawAcceleration, SmoothedAcceleration, p);
        }
Example #41
0
        void OnAccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs args)
        {
            string str = String.Format("X = {0:F2}\n" +
                                       "Y = {1:F2}\n" +
                                       "Z = {2:F2}\n\n" +
                                       "Magnitude = {3:F2}\n\n" +
                                       "{4}",
                                       args.X, args.Y, args.Z,
                                       Math.Sqrt(args.X * args.X + args.Y * args.Y +
                                                 args.Z * args.Z),
                                       args.Timestamp);

            if (txtblk.CheckAccess())
            {
                SetTextBlockText(txtblk, str);
            }
            else
            {
                txtblk.Dispatcher.BeginInvoke(new SetTextBlockTextDelegate(SetTextBlockText),
                                              txtblk, str);
            }
        }
Example #42
0
        void OnAccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs args)
        {
            string str = String.Format("X = {0:F2}\n" +
                                       "Y = {1:F2}\n" +
                                       "Z = {2:F2}\n\n" +
                                       "Magnitude = {3:F2}\n\n" +
                                       "{4}",
                                       args.X, args.Y, args.Z,
                                       Math.Sqrt(args.X * args.X + args.Y * args.Y +
                                                                   args.Z * args.Z),
                                       args.Timestamp);

            if (txtblk.CheckAccess())
            {
                SetTextBlockText(txtblk, str);
            }
            else
            {
                txtblk.Dispatcher.BeginInvoke(new SetTextBlockTextDelegate(SetTextBlockText),
                                              txtblk, str);
            }
        }
        private void ThreadedReadingChanged(AccelerometerReadingEventArgs e)
        {
            if (this.accelerometer != null)
            {
                var state = this.accelerometer.State;

                if (state == SensorState.Ready)
                {
                    this.CallbackName = this.successCallback;

                    this.CallbackArgs = new[]
                                            {
                                                e.X.ToString("0.00"),
                                                e.Y.ToString("0.00"),
                                                e.Z.ToString("0.00"),
                                                e.Timestamp.ToString()
                                            };
                    this.SendAsyncResponse();
                }
                else
                {
                    this.CallbackName = this.errorCallback;
                    this.CallbackArgs = new[] { state.ToString() };
                    this.SendAsyncResponse();
                }

                try
                {
                    this.accelerometer.Stop();
                    this.accelerometer.Dispose();
                    this.accelerometer = null;
                }
                catch
                {
                    // NOOP - We don't, currently, care if we can't stop the accelerometer
                }
            }
        }
Example #44
0
 private void accelSensor_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
 {
     accelReading.X = (float)e.X;
     accelReading.Y = (float)e.Y;
     accelReading.Z = (float)e.Z;
 }
        /// <summary>
        /// Called on accelerometer sensor sample available.
        /// Main accelerometer data filtering routine
        /// </summary>
        /// <param name="sender">Sender of the event.</param>
        /// <param name="e">AccelerometerReadingAsyncEventArgs</param>
        private void sensor_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {
            Simple3DVector lowPassFilteredAcceleration;
            Simple3DVector optimalFilteredAcceleration;
            Simple3DVector averagedAcceleration;
            Simple3DVector rawAcceleration = new Simple3DVector(e.X, e.Y, e.Z);

            lock (_sampleBuffer)
            {
                if (!_initialized)
                { // Initialize file with 1st value
                    _sampleSum = rawAcceleration * SamplesCount;
                    _averageAcceleration = rawAcceleration;

                    // Initialize file with 1st value
                    for (int i = 0; i < SamplesCount; i++)
                    {
                        _sampleBuffer[i] = _averageAcceleration;
                    }

                    _previousLowPassOutput = _averageAcceleration;
                    _previousOptimalFilterOutput = _averageAcceleration;

                    _initialized = true;
                }

                // low-pass filter
                lowPassFilteredAcceleration = new Simple3DVector(
                    LowPassFilter(rawAcceleration.X, _previousLowPassOutput.X),
                    LowPassFilter(rawAcceleration.Y, _previousLowPassOutput.Y),
                    LowPassFilter(rawAcceleration.Z, _previousLowPassOutput.Z));
                _previousLowPassOutput = lowPassFilteredAcceleration;

                // optimal filter
                optimalFilteredAcceleration = new Simple3DVector(
                    FastLowAmplitudeNoiseFilter(rawAcceleration.X, _previousOptimalFilterOutput.X),
                    FastLowAmplitudeNoiseFilter(rawAcceleration.Y, _previousOptimalFilterOutput.Y),
                    FastLowAmplitudeNoiseFilter(rawAcceleration.Z, _previousOptimalFilterOutput.Z));
                _previousOptimalFilterOutput = optimalFilteredAcceleration;

                // Increment circular buffer insertion index
                _sampleIndex++;
                if (_sampleIndex >= SamplesCount) _sampleIndex = 0; // if at max SampleCount then wrap samples back to the beginning position in the list

                // Add new and remove old at _sampleIndex
                Simple3DVector newVect = optimalFilteredAcceleration;
                _sampleSum += newVect;
                _sampleSum -= _sampleBuffer[_sampleIndex];
                _sampleBuffer[_sampleIndex] = newVect;

                averagedAcceleration = _sampleSum / SamplesCount;
                _averageAcceleration = averagedAcceleration;

                // Stablity check
                // If current low-pass filtered sample is deviating for more than 1/100 g from average (max of 0.5 deg inclination noise if device steady)
                // then reset the stability counter.
                // The calibration will be prevented until the counter is reaching the sample count size (calibration enabled only if entire
                // sampling buffer is "stable"
                Simple3DVector deltaAcceleration = averagedAcceleration - optimalFilteredAcceleration;
                if ((Math.Abs(deltaAcceleration.X) > _maximumStabilityDeltaOffset) ||
                    (Math.Abs(deltaAcceleration.Y) > _maximumStabilityDeltaOffset) ||
                    (Math.Abs(deltaAcceleration.Z) > _maximumStabilityDeltaOffset))
                { // Unstable
                    _deviceStableCount = 0;
                }
                else
                {
                    if (_deviceStableCount < SamplesCount) ++_deviceStableCount;
                }

                // Add calibrations
                rawAcceleration += ZeroAccelerationCalibrationOffset;
                lowPassFilteredAcceleration += ZeroAccelerationCalibrationOffset;
                optimalFilteredAcceleration += ZeroAccelerationCalibrationOffset;
                averagedAcceleration += ZeroAccelerationCalibrationOffset;
            }

            if (ReadingChanged != null)
            {
                AccelerometerHelperReadingEventArgs readingEventArgs = new AccelerometerHelperReadingEventArgs();

                readingEventArgs.RawAcceleration = rawAcceleration;
                readingEventArgs.LowPassFilteredAcceleration = lowPassFilteredAcceleration;
                readingEventArgs.OptimalyFilteredAcceleration = optimalFilteredAcceleration;
                readingEventArgs.AverageAcceleration = averagedAcceleration;

                ReadingChanged(this, readingEventArgs);
            }
        }
Example #46
0
 void OnAccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs args)
 {
     lock (accelerationLock)
     {
         acceleration = 0.5f * oldAcceleration +
                        0.5f * new Vector3((float)args.X, (float)args.Y, (float)args.Z);
         oldAcceleration = acceleration;
     }
 }
 private void ReadingChanged(object sender, AccelerometerReadingEventArgs e)
 {
     //Code for checking shake detection
     if (_sensor.State == SensorState.Ready)
     {
         AccelerometerReadingEventArgs reading = e;
         try
         {
             if (_lastReading != null)
             {
                 if (!_shaking && CheckForShake(_lastReading, reading, ShakeThreshold) && _shakeCount >= 1)
                 {
                     //We are shaking
                     _shaking = true;
                     _shakeCount = 0;
                     OnShakeDetected();
                 }
                 else if (CheckForShake(_lastReading, reading, ShakeThreshold))
                 {
                     _shakeCount++;
                 }
                 else if (!CheckForShake(_lastReading, reading, 0.2))
                 {
                     _shakeCount = 0;
                     _shaking = false;
                 }
             }
             _lastReading = reading;
         }
         catch
         {
             /* ignore errors */
         }
     }
 }
Example #48
0
 void acc_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
 {
     Deployment.Current.Dispatcher.BeginInvoke(() => minhaLeitura(e));
 }
 public void AccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs e)
 {
     accelReading.X = (float)e.X;
     accelReading.Y = (float)e.Y;
     accelReading.Z = (float)e.Z;
 }
 private void OnAccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs args)
 {
     RecordReading(ReadingValue(args));
 }
 /// <summary>
 /// This method is called from the accelerometer service thread. We should not
 /// modify our data in this method (invoked from a different thread). Instead, 
 /// we will create a Lambda Expression, and allow our own thread to make the 
 /// function call to MoveBall.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 void AccMeterChange(object sender, AccelerometerReadingEventArgs e)
 {
     // event comes from a separate thread (system thread)
     // => creates a Lambda Expression: a thread-safe way of calling MoveBall(e).
     Deployment.Current.Dispatcher.BeginInvoke(() => UpdateBallAcceleration(e));
 }
Example #52
0
 void OnAccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs args)
 {
     lock (accelerometerVectorLock)
     {
         accelerometerVector = new Vector3((float)args.X, (float)args.Y, (float)args.Z);
     }
 }
 public void AccelerometerDataChanged(object sender, AccelerometerReadingEventArgs e)
 {
     // Store accelerometer data
     accelerometerData.X = (float)e.X;
     accelerometerData.Y = (float)e.Y;
 }
 private void AccelerometerReadingChanged(object sender, AccelerometerReadingEventArgs e)
 {
     Deployment.Current.Dispatcher.BeginInvoke(() => this.ThreadedReadingChanged(e));
 }
            void UpdateBallAcceleration(AccelerometerReadingEventArgs e)
            {
                // by default, XNA App works in landscape mode, while
                // accelerometer assumes portrait.
                //    XYZ ranges are betwen -2 and +2
                // Gravitatoin pull is -1
                //
                const float kAccelerationScale = 0.5f;
                float x = kAccelerationScale * (float)e.X;
                float y = kAccelerationScale * (float)e.Y;
                mAccValues.Z = kAccelerationScale * (float)e.Z;

                switch (mCurrentOrientation)
                {
                    case DisplayOrientation.Portrait:
                        mAccValues.X = x;
                        mAccValues.Y = -y;
                        break;
                    case DisplayOrientation.LandscapeLeft:
                        mAccValues.X = -y;
                        mAccValues.Y = -x;
                        break;
                    case DisplayOrientation.LandscapeRight:
                        mAccValues.X = y;
                        mAccValues.Y = x;
                        break;
                }
            }
Example #56
0
 void acc_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
 {
     // throw new NotImplementedException();
     Dispatcher.BeginInvoke(() =>
     {
         if (this.Orientation == PageOrientation.LandscapeLeft)
         {
             dirRotation -= e.Y;
             angle -= e.Y;
         }
         else
         {
             dirRotation += e.Y;
             angle += e.Y;
         }
     });
 }
Example #57
0
 void OnAccelerometerReadingChanged( object sender,AccelerometerReadingEventArgs e )
 {
     MotionEvent( BBGameEvent.MotionAccel,0,(float)e.X,-(float)e.Y,(float)e.Z );
 }
Example #58
0
 void minhaLeitura(AccelerometerReadingEventArgs e)
 {
     if (acc != null)
     {
         //txtbToqueDados.Text = e.Y.ToString() + "   " +e.Z.ToString();
         if (e.Z < -0.4)
         {
             if (go == false)
             {
                 Thread t = new Thread(jogando);
                 t.Start();
                 txtbToqueDados.Text = "Jogando...";
             }
             else
             {
                 txtbToqueDados.Text = "Toque nos dados ou toque no botão acima e mexa o celular para jogar";
                 go = false;
             }
             acc.Stop();
             acc = null;
             txtbStatusAcelerômetro.Text = "Acelerômetro parado";
         }
     }
 }
		/// <summary>
		/// Our accelerometer ReadingChanged event handler.
		/// </summary>
		/// <param name="sender">The sender.</param>
		/// <param name="e">The AccelerometerReadingEventArgs.</param>
		private void accelerometer_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
		{
			Vector2 result;
			double x, y;
			switch (Game.Window.CurrentOrientation)
			{
				case DisplayOrientation.LandscapeLeft:
					{
						//System.Diagnostics.Debug.WriteLine("LandscapeLeft");
						x = -(e.Y + tiltLeftRightAdjustment);
						y = e.Z + tiltTowardAwayAdjustment;
					}
					break;

				case DisplayOrientation.LandscapeRight:
					//System.Diagnostics.Debug.WriteLine("LandscapeRight");
					x = e.Y + tiltLeftRightAdjustment;
					y = e.Z + tiltTowardAwayAdjustment;
					break;

				case DisplayOrientation.Portrait:
					// A bug in the framework requires this bit of hack-y workaround code.
					if (isActuallyLandscapeLeft)
					{
						//System.Diagnostics.Debug.WriteLine("LandscapeLeft portrait hack");
						x = -(e.Y + tiltLeftRightAdjustment);
						y = e.Z + tiltTowardAwayAdjustment;
					}
					else
					{
						//System.Diagnostics.Debug.WriteLine("Portrait");
						x = e.X + tiltLeftRightAdjustment;
						y = e.Z + tiltTowardAwayAdjustment;
					}
					break;

				default:
					System.Diagnostics.Debug.WriteLine("DisplayOrientation.Default? This will not end well...");
					x = e.Y + tiltLeftRightAdjustment;
					y = -(e.Z + tiltTowardAwayAdjustment);
					break;
			}

			if (WriteOutDiagnostics)
			{
				System.Diagnostics.Debug.WriteLine("{0} {1} {2}", e.X.ToString("F2"), e.Y.ToString("F2"), e.Z.ToString("F2"));
			}

			// Create the adjusted data result. We apply a power curve, multiply by 100, and then cast to
			// an int to ditch remainders and avoid excess precision that we don't really care about. You can
			// adjust this as desired.
			result = new Vector2(
				(int)((Math.Pow((x < 0 ? -x : x), powerCurveValue) * (x < 0 ? -1 : 1)) * 100),
				(int)((Math.Pow((y < 0 ? -y : y), powerCurveValue) * (y < 0 ? -1 : 1)) * 100));

			// Lock while we update rawAccelerometerData with the new reading.
			lock (accelerometerDataLock)
			{
                // If accelerometer is null and we should thus ignore this reading.
                if (accelerometer == null)
                {
                    return;
                }

				// Set hasReceivedAccelerometerData to true so that we know that we're getting data.
				HasReceivedAccelerometerData = true;

				// Add the latest raw data to the raw data queue.
				accelerometerDataQueue.Enqueue(new Vector3((float)e.X, (float)e.Y, (float)e.Z));

				// Add the latest data to the adjusted data queue.
				adjustedAccelerometerDataQueue.Enqueue(result);

				// If the length of the queues are greater than numberOfReadingsToAverage, remove the earliest readings.
				if (accelerometerDataQueue.Count > numberOfReadingsToAverage)
				{
					accelerometerDataQueue.Dequeue();
				}
				if (adjustedAccelerometerDataQueue.Count > numberOfReadingsToAverage)
				{
					adjustedAccelerometerDataQueue.Dequeue();
				}

				// Reset rawAccelerometerData to all zeroes so that we can average it.
				rawAccelerometerData = Vector3.Zero;
				// Reset adjustedAccelerometerData to all zeroes so that we can average it.
				adjustedAccelerometerData = Vector2.Zero;

				// Add each reading to rawAccelerometerData
				foreach (var item in accelerometerDataQueue)
				{
					rawAccelerometerData += item;
				}

				foreach (var item in adjustedAccelerometerDataQueue)
				{
					adjustedAccelerometerData += item;
				}


				// Divide each element by the number of items contained in the queue to get the average
				// and cast as an int to get rid of excess precision that we don't want.
				rawAccelerometerData.X = (rawAccelerometerData.X / accelerometerDataQueue.Count);
				rawAccelerometerData.Y = (rawAccelerometerData.Y / accelerometerDataQueue.Count);
				rawAccelerometerData.Z = (rawAccelerometerData.Z / accelerometerDataQueue.Count);

				adjustedAccelerometerData.X = (int)(adjustedAccelerometerData.X / adjustedAccelerometerDataQueue.Count);
				adjustedAccelerometerData.Y = (int)(adjustedAccelerometerData.Y / adjustedAccelerometerDataQueue.Count);
			}
		}
Example #60
0
        private void OnSensorReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {
            if (jogoTerminou)
                return;

            if (e.X != lastX && e.Y != lastY && e.Z != lastZ)
            {
                houveModificacao = true;
                var difX = (e.X - lastX);
                if (difX < 0)
                    difX *= -1;

                var difY = (e.Y - lastY);
                if (difY < 0)
                    difY *= -1;

                var difZ = (e.Z - lastZ);
                if (difZ < 0)
                    difZ *= -1;

                this.forcaAtual += (difX + difY + difZ) + 0.5;

                lastX = e.X;
                lastY = e.Y;
                lastZ = e.Z;
            }

            if (this.forcaAtual >= 0 && checarSeNaoHouve && (this.lastTickX != e.X && lastTickY != e.Y && lastTickZ != e.Z))
            {
                checarSeNaoHouve = false;
                this.forcaAtual -= 5;
            }

            if (checarSeNaoHouve)
            {
                this.lastTickX = e.X;
                this.lastTickY = e.Y;
                this.lastTickZ = e.Z;
            }

            Deployment.Current.Dispatcher.BeginInvoke(() =>
            {
                if (forcaAtual >= this.pbForce.Maximum)
                {
                    this.jogoTerminou = true;
                    this.BalancoDoSino.Stop();
                    soundInstance.Stop();
                }
            });
        }