public double GetAccelerationX()
        {
            if (_accelerometer != null)
            {
                AccelerometerReading reading = _accelerometer.GetCurrentReading();

                if (reading != null)
                {
                    return(reading.AccelerationX);
                }
            }

            return(0.0);
        }
Esempio n. 2
0
        /// <summary>
        /// Gets the current sensor value.
        /// </summary>
        /// <returns>
        /// The current sensor value. If no value is available, <c>null</c> will be returned.
        /// </returns>
        public override IAccelerometerValue GetCurrentValue()
        {
            var currentValue = _sensor.GetCurrentReading();

            return(new AccelerometerValue(currentValue.Timestamp, currentValue.AccelerationX,
                                          currentValue.AccelerationY, currentValue.AccelerationZ));
        }
Esempio n. 3
0
        private void OnGetAccelerometer(object sender, RoutedEventArgs e)
        {
            Accelerometer        accelerometer = Accelerometer.GetDefault();
            AccelerometerReading reading       = accelerometer.GetCurrentReading();

            this.DefaultViewModel["AccelerometerResult"] = GetAccelerometerResult(reading);
        }
Esempio n. 4
0
        public void PrintSensors(bool fast = false)
        {
            //BarometerReading read = baro.GetCurrentReading();
            var accR = acc.GetCurrentReading();
            //Debug.WriteLine(Math.Sqrt(Math.Pow(accR.AccelerationX; 2) + Math.Pow(accR.AccelerationY; 2) + Math.Pow(accR.AccelerationZ; 2)) + " (" + accR.AccelerationX + "/" + accR.AccelerationX + "/" + accR.AccelerationX + ")");
            //var actR = act.GetCurrentReadingAsync().GetResults();
            //Debug.WriteLine(actR.Activity + " (" + actR.Confidence + ")");
            //Debug.WriteLine(alt.GetCurrentReading().AltitudeChangeInMeters);
            //Debug.WriteLine(baro.GetCurrentReading().StationPressureInHectopascals);
            var compR = comp.GetCurrentReading();
            //Debug.WriteLine(compR.HeadingMagneticNorth + " (+/-" + compR.HeadingAccuracy + ")");
            var gyroR = gyro.GetCurrentReading();
            //Debug.WriteLine("(" + gyroR.AngularVelocityX + "/" + gyroR.AngularVelocityY + "/" + gyroR.AngularVelocityZ + ")");
            var incR = inc.GetCurrentReading();
            //Debug.WriteLine("(" + incR.PitchDegrees + "/" + incR.RollDegrees + "/" + incR.YawDegrees + ")");
            //var psR=ps.GetCurrentReading();
            //Debug.WriteLine(psR.IsDetected + ": " + psR.DistanceInMillimeters);
            //Debug.WriteLine(sos.GetCurrentOrientation());



            String csv = (Math.Sqrt(Math.Pow(accR.AccelerationX, 2) + Math.Pow(accR.AccelerationY, 2) + Math.Pow(accR.AccelerationZ, 2)) + ";" + accR.AccelerationX + ";" + accR.AccelerationY + ";" + accR.AccelerationZ + ";"
                          + alt.GetCurrentReading().AltitudeChangeInMeters + ";" + baro.GetCurrentReading().StationPressureInHectopascals + ";" + compR.HeadingMagneticNorth + ";" + compR.HeadingTrueNorth + ";" + compR.HeadingAccuracy
                          + ";" + gyroR.AngularVelocityX + ";" + gyroR.AngularVelocityY + ";" + gyroR.AngularVelocityZ + ";" + incR.PitchDegrees + ";" + incR.RollDegrees + ";" + incR.YawDegrees + ";" + sos.GetCurrentOrientation() + ";" + accR.Timestamp.ToUnixTimeMilliseconds() + ";" + fast);

            Debug.WriteLine(csv);
            StorageInterface.AppendToKnownStorageFile(Token, csv + "\r\n").GetAwaiter();
            OUT.Text += csv + "\r\n";
        }
        private async void SendDeviceToCloudMessagesAsync()
        {
            byte[]  byteData;
            string  JSONString = "";
            Message EventToSend;

            count++;
            if (chkGoSlow.IsChecked == true)
            {
                if (count % 10 != 0)
                {
                    return;
                }
            }
            // Calculate Accelleration and Position
            Accelerometer        accelerometer = Accelerometer.GetDefault();
            AccelerometerReading r             = accelerometer.GetCurrentReading();
            double G = Math.Sqrt((r.AccelerationX * r.AccelerationX) + (r.AccelerationY * r.AccelerationY) + (r.AccelerationZ * r.AccelerationZ));

            // Create JSON String
            JSONString = "{\"DataTypeKey\": \"ACC\", \"Count\": " + count + ", \"X\": " + Math.Round(r.AccelerationX, 2) + ", \"Y\": " + Math.Round(r.AccelerationY, 2) + ", \"Z\": " + Math.Round(r.AccelerationZ, 2) + ", \"G\": " + Math.Round(G, 2) + "}";

            Label1.Text = JSONString;
            byteData    = Encoding.UTF8.GetBytes(JSONString);
            EventToSend = new Message(byteData);

            if (sending == 1)
            {
                await deviceClient.SendEventAsync(EventToSend);
            }
        }
        public async void NewAcc(Accelerometer sender, AccelerometerReadingChangedEventArgs args)
        {
            var reading = args == null?sender?.GetCurrentReading() : args.Reading;

            await this.dispatcher.RunAsync(
                CoreDispatcherPriority.Normal,
                () =>
            {
                this[ACCELERATOR] = reading == null
                                                ? this[ACCELERATOR].New()
                                                : this[ACCELERATOR].New(
                    reading.AccelerationX,
                    reading.AccelerationY,
                    reading.AccelerationZ,
                    0);
                if (this[ACCELERATOR].IsChanged)
                {
                    this.OnPropertyChanged(new PropertyChangedEventArgs("ItemsList"));
                    this.OnSensorUpdated?.Invoke(this[ACCELERATOR]);
                }
            });

            if (this.SensorSwitches.A.HasValue && (this.SensorSwitches.A.Value == 1 || this.SensorSwitches.A.Value == 3))
            {
                this.SensorSwitches.A = 0;
            }
        }
Esempio n. 7
0
        /// <summary>
        /// This is the dispatcher callback.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void DisplayCurrentReading(object sender, object args)
        {
            AccelerometerReading reading = _accelerometer.GetCurrentReading();

            if (reading != null)
            {
                MainPage.SetReadingText(ScenarioOutput, reading);
            }
        }
        void _myDispatcherTimer_Tick(object sender, object e)
        {
            AccelerometerReading reading = _accelerometer.GetCurrentReading();

            if (reading != null)
            {
                ValuesHandler(reading);
            }
        }
Esempio n. 9
0
        private void OnTick(object sender, object e)
        {
            Initialize();

            if (accelerometer != null)
            {
                AccelerometerReading reading = accelerometer.GetCurrentReading();

                if (reading != null)
                {
                    //Debug.WriteLine(reading.AccelerationX + ", " + reading.AccelerationY);

                    const double multiplier = 15;

                    // Increment speed and move object.
                    speedX    += reading.AccelerationX;
                    positionX += speedX;

                    if (positionX < 0)
                    {
                        positionX = 0;

                        // Invert direction.
                        speedX *= -1;
                    }
                    else if (positionX > myCanvas.ActualWidth - rectangle.Width)
                    {
                        positionX = myCanvas.ActualWidth - rectangle.Width;

                        // Invert direction.
                        speedX *= -1;
                    }

                    // Increment speed and move object.
                    speedY    += reading.AccelerationY;
                    positionY -= speedY;

                    if (positionY < 0)
                    {
                        positionY = 0;

                        // Invert direction.
                        speedY *= -1;
                    }
                    else if (positionY > myCanvas.ActualHeight - rectangle.Height)
                    {
                        positionY = myCanvas.ActualHeight - rectangle.Height;

                        // Invert direction.
                        speedY *= -1;
                    }

                    rectangle.SetValue(Canvas.LeftProperty, positionX);
                    rectangle.SetValue(Canvas.TopProperty, positionY);
                }
            }
        }
Esempio n. 10
0
        /// <summary>
        /// This is the dispatcher callback.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void DisplayCurrentReading(object sender, object args)
        {
            AccelerometerReading reading = _accelerometer.GetCurrentReading();

            if (reading != null)
            {
                ScenarioOutput_X.Text = String.Format("{0,5:0.00}", reading.AccelerationX);
                ScenarioOutput_Y.Text = String.Format("{0,5:0.00}", reading.AccelerationY);
                ScenarioOutput_Z.Text = String.Format("{0,5:0.00}", reading.AccelerationZ);
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Update Accelerometer readings event and update UI
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">The <see cref="object"/> instance containing the event data.</param>
        private void UpdateAccelerometer(object sender, EventArgs e)
        {
            try
            {
                Accelerometer accelero = Accelerometer.GetDefault();
                if (accelero != null)
                {
                    XPanel.Text = LocRM.GetString("XAxis") + ": " +
                                  String.Format("{0,5:0.00}", accelero.GetCurrentReading().AccelerationX) + "G";
                    YPanel.Text = LocRM.GetString("YAxis") + ": " +
                                  String.Format("{0,5:0.00}", accelero.GetCurrentReading().AccelerationY) + "G";
                    ZPanel.Text = LocRM.GetString("ZAxis") + ": " +
                                  String.Format("{0,5:0.00}", accelero.GetCurrentReading().AccelerationZ) + "G";

                    //set the x,y of red panel
                    double x      = Math.Min(1, accelero.GetCurrentReading().AccelerationX);
                    double y      = Math.Min(1, accelero.GetCurrentReading().AccelerationY);
                    double square = x * x + y * y;
                    if (square > 1)
                    {
                        x /= Math.Sqrt(square);
                        y /= Math.Sqrt(square);
                    }
                    double locationX = Math.Max(0, 100 + 100 * x);
                    locationX = Math.Min(200, 100 + 100 * x);
                    double locationY = Math.Max(0, 100 - 100 * y);
                    locationY = Math.Min(200, 100 - 100 * y);
                    this.RedPanel.Location = new Point((int)locationX, (int)locationY);
                }
                else
                {
                    XPanel.Text = LocRM.GetString("NotFound");
                    _timer.Stop();
                }
            }
            catch (Exception ex)
            {
                _timer.Stop();
                DllLog.Log.LogError(ex.ToString());
            }
        }
Esempio n. 12
0
 async void OnMainPageLoaded(object sender, RoutedEventArgs args)
 {
     if (accelerometer != null)
     {
         accelerometer.ReportInterval = accelerometer.MinimumReportInterval;
         SetBubble(accelerometer.GetCurrentReading());
         accelerometer.ReadingChanged += OnAccelerometerReadingChanged;
     }
     else
     {
         await new MessageDialog("Accelerometer is not available").ShowAsync();
     }
 }
 void ReadAccelerometerData()
 {
     if (accelSensor != null)
     {
         AccelerometerReading reading = accelSensor.GetCurrentReading();
         if (reading != null)
         {
             accelX.Value = reading.AccelerationX;
             accelY.Value = reading.AccelerationY;
             accelZ.Value = reading.AccelerationZ;
         }
     }
 }
Esempio n. 14
0
        void AcceShowData()
        {
            double xa = 0;
            double ya = 0;
            double za = 0;

            accelerometerReading = accelerometer.GetCurrentReading();
            //读取数据
            xa = 9.81 * accelerometerReading.AccelerationX;
            ya = 9.81 * accelerometerReading.AccelerationY;
            za = 9.81 * accelerometerReading.AccelerationZ;

            //处理,计算数据
            double dt = 1;//accelerometer.MinimumReportInterval;

            //if (ya != 0)
            //{
            an++;
            v.Add(v[an - 1] + dt * xa);
            // xv.Add(xv[an - 1] + dt * xa);
            //yv.Add(yv[an - 1] + dt * xa);
            //zv.Add(zv[an - 1] + dt * xa);
            //v.Add(vector_add(xv[an], yv[an], zv[an]));
            if (unitflag == true)
            {
                speed.Text = v[an].ToString("0.00");
                unit1.Text = "m/s";
            }
            if (unitflag == false)
            {
                double vkm = v[an] / 3.6;
                speed.Text = vkm.ToString("0.0");
                unit1.Text = "km/h";
            }
            //}
            //显示加速传感器得到的速度数值
            // xspeed.Text = "x: " + xv[an].ToString("0.00");
            //yspeed.Text = "y: " + yv[an].ToString("0.00");
            //zspeed.Text = "z: " + zv[an].ToString("0.00");
            //else
            // { }
            xspeed.Text = xa.ToString("0.00");
            yspeed.Text = ya.ToString("0.00");
            zspeed.Text = za.ToString("0.00");

            /*
             * xspeed.Text = accelerometerReading.AccelerationX.ToString("0.00");
             * yspeed.Text = accelerometerReading.AccelerationY.ToString("0.00");
             * zspeed.Text = accelerometerReading.AccelerationZ.ToString("0.00");
             * */
        }
        public void OnGetAccelerometer()
        {
            Accelerometer sensor = Accelerometer.GetDefault();

            if (sensor != null)
            {
                AccelerometerReading reading = sensor.GetCurrentReading();
                AccelerometerInfo = $"X: {reading.AccelerationX} Y: {reading.AccelerationY} Z: {reading.AccelerationZ}";
            }
            else
            {
                AccelerometerInfo = "Compass not found";
            }
        }
        private async Task ReadAcc(int timerSeconds)
        {
            if (_accelerometer != null)
            {
                AccelerometerReading reading = _accelerometer.GetCurrentReading();
                if (reading != null)
                {
                    acc_x = Math.Abs(reading.AccelerationX);
                    acc_y = Math.Abs(reading.AccelerationY);
                    acc_z = Math.Abs(reading.AccelerationZ);
                    ScenarioOutput_X.Text = "X : " + String.Format("{0,5:0.00}", reading.AccelerationX);
                    ScenarioOutput_Y.Text = "Y : " + String.Format("{0,5:0.00}", reading.AccelerationY);
                    ScenarioOutput_Z.Text = "Z : " + String.Format("{0,5:0.00}", reading.AccelerationZ);


                    // TODO : CHECK CONDITIONS FOR THIS
                    // Critical Step. Any component of acceleration crossing the precalculated limit of 39.2 will trigger
                    // the clicking of the StartApp button with the parameter HighAccEvent set as true.
                    if ((acc_x >= 2.0 && !prev_xg) || (acc_y >= 2.0 && !prev_yg) || (acc_z >= 2.0 && !prev_zg))
                    {
                        Send_Click(null, null);
                        HighAccEvent = true;
                        MainPage.DisplayToast("High Acceleration Event Encountered");
                        await Get_GeoPosition();
                        await Send_Message();
                    }

                    else if (timerSeconds % 4 == 0)
                    {
                        if (acc_x > 0.80 && acc_x < 1.20)
                        {
                            prev_xg = true; prev_yg = false; prev_zg = false;
                        }
                        else if (acc_y > 0.80 && acc_y < 1.20)
                        {
                            prev_yg = true; prev_xg = false; prev_zg = false;
                        }
                        else if (acc_z > 0.80 && acc_z < 1.20)
                        {
                            prev_zg = true; prev_xg = false; prev_yg = false;
                        }
                    }
                }
            }
            else
            {
                rootPage.NotifyUser("No Accelerometer found. This app is not compatible with your device.", NotifyType.ErrorMessage);
            }
        }
Esempio n. 17
0
        void OnCompositionTargetRendering(object sender, object args)
        {
            AccelerometerReading reading = accelerometer.GetCurrentReading();

            if (reading == null)
            {
                return;
            }

            // Get elapsed time since last event
            TimeSpan timeSpan       = (args as RenderingEventArgs).RenderingTime;
            double   elapsedSeconds = (timeSpan - this.timeSpan).TotalSeconds;

            this.timeSpan = timeSpan;

            // Convert accelerometer reading to display coordinates
            double x = reading.AccelerationX;
            double y = -reading.AccelerationY;

            // Get current X-Y acceleration and smooth it
            acceleration = 0.5 * (acceleration + new Vector2(x, y));

            // Calculate new velocity and position
            ballVelocity += GRAVITY * acceleration * elapsedSeconds;
            ballPosition += ballVelocity * elapsedSeconds;

            // Check for hitting edge
            if (ballPosition.X - BALL_RADIUS < 0)
            {
                ballPosition = new Vector2(BALL_RADIUS, ballPosition.Y);
                ballVelocity = new Vector2(0, ballVelocity.Y);
            }
            if (ballPosition.X + BALL_RADIUS > this.ActualWidth)
            {
                ballPosition = new Vector2(this.ActualWidth - BALL_RADIUS, ballPosition.Y);
                ballVelocity = new Vector2(0, ballVelocity.Y);
            }
            if (ballPosition.Y - BALL_RADIUS < 0)
            {
                ballPosition = new Vector2(ballPosition.X, BALL_RADIUS);
                ballVelocity = new Vector2(ballVelocity.X, 0);
            }
            if (ballPosition.Y + BALL_RADIUS > this.ActualHeight)
            {
                ballPosition = new Vector2(ballPosition.X, this.ActualHeight - BALL_RADIUS);
                ballVelocity = new Vector2(ballVelocity.X, 0);
            }
            ball.Center = new Point(ballPosition.X, ballPosition.Y);
        }
        // Attach event handlers
        protected override void OnNavigatedTo(NavigationEventArgs args)
        {
            if (accelerometer != null)
            {
                SetAccelerometerText(accelerometer.GetCurrentReading());
                accelerometer.ReadingChanged += OnAccelerometerReadingChanged;
            }

            if (simpleOrientationSensor != null)
            {
                SetSimpleOrientationText(simpleOrientationSensor.GetCurrentOrientation());
                simpleOrientationSensor.OrientationChanged += OnSimpleOrientationChanged;
            }
            base.OnNavigatedTo(args);
        }
Esempio n. 19
0
        public AccelerometerReading GetAccelerometerReading()
        {
            if (_accelerometer == null)
            {
                throw new InvalidOperationException("The accelerometer is either not present or has not been initialized");
            }

            var reading = _accelerometer.GetCurrentReading();

            return(reading);
            // Available reading values include:
            // reading.AccelerationX
            // reading.AccelerationY
            // reading.AccelerationZ
            // reading.Timestamp
        }
Esempio n. 20
0
        //摸圆圈儿触发
        public async void Get_Acce_Data(object sender, RoutedEventArgs e)
        {
            Init();
            //修改zero圆圈的颜色

            /*
             * var img = new Uri("ms-appx://Assets/zero.png", UriKind.Absolute);
             * ImageBrush ib = new ImageBrush();
             * ib.ImageSource = new BitmapImage(img);
             * zero.Fill = ib;
             */
            //if (run_state == false)
            //{
            run_state     = true;
            accelerometer = Accelerometer.GetDefault();
            if (accelerometer == null)
            {
                await new MessageDialog("您的手机不支持加速度传感器").ShowAsync();
                return;
            }
            else
            {
                //xv.Add(0); yv.Add(0); zv.Add(0);
                v.Add(0);
                //最小时间间隔
                accelerometer.ReportInterval = accelerometer.MinimumReportInterval;
                //加速度变化
                accelerometer.ReadingChanged += accelerometer_ReadingChanged;
                //手机晃动
                accelerometer.Shaken += accelerometer_Shaken;
                //读取加速度数据
                accelerometerReading = accelerometer.GetCurrentReading();
                //显示数据
                AcceShowData();
                dispatcherTimer.Start();
            }

            Get_GPS_Data();
            // }
            // else
            // {
            //     run_state = false;
            //     dispatcherTimer.Stop();
            //      Init();
            // }
        }
        private void IMUTimer_Tick(object StateObject)
        {
            string timeStamp = nanoTime().ToString();

            if (DEBUG)
            {
                writerCSV.WriteLine(timeStamp + "," + "omega_x" + "," + "omega_y" + "," + "omega_z" + "," + "alpha_x" + "," + "alpha_y" + "," + "alpha_z");
            }
            else
            {
                AccelerometerReading readingAccl = _accelerometer.GetCurrentReading();
                GyrometerReading     readingGyro = _gyrometer.GetCurrentReading();

                writerCSV.WriteLine(timeStamp + ","
                                    + readingGyro.AngularVelocityX + "," + readingGyro.AngularVelocityY + "," + readingGyro.AngularVelocityZ
                                    + "," + readingAccl.AccelerationX + "," + readingAccl.AccelerationY + "," + readingAccl.AccelerationZ);
            }
        }
Esempio n. 22
0
        private void ProcessState()
        {
            LidPositions position = (LidPositions)(uint)accelerometer.GetCurrentReading()
                                    .Properties[AccelerometerPropertyId];

            if (lastPosition == position)
            {
                return;
            }

            lastPosition = position;

            bool shouldInputBeBlocked = lastPosition > LidPositions.Open180deg;

            if (isKeyboardDisabled != shouldInputBeBlocked)
            {
                SetKeyboardState(shouldInputBeBlocked);
            }
        }
Esempio n. 23
0
        void GetAccelerometerReading()
        {
            // Check we have an accelerometer to read...
            if (_accelerometer == null)
            {
                AccelerometerData = Vector3.Zero;
                _accText.Text     = "No accelerometer available.";
            }
            else
            {
                // Get the current accelerometer reading
                AccelerometerReading accData = _accelerometer.GetCurrentReading();
                // Translate it into a Vector3 structure
                AccelerometerData = new Vector3((float)accData.AccelerationX, (float)accData.AccelerationY, (float)accData.AccelerationZ);

                // Update the content of the text object
                _accText.Text = "Accelerometer data:\n" + AccelerometerData.X.ToString("0.000")
                                + ", " + AccelerometerData.Y.ToString("0.000")
                                + ", " + AccelerometerData.Z.ToString("0.000");
            }
        }
        void dt_Tick(object sender, EventArgs e)
        {
            var rd = acc.GetCurrentReading();

            if (Math.Abs(count) > 0.3)
            {
                if (count < 0 && current > 0)
                {
                    current--;
                }
                if (count > 0 && current < list.Count - 1)
                {
                    current++;
                }
                Display();
                count = 0;
            }
            else
            {
                count += rd.AccelerationX;
            }
        }
Esempio n. 25
0
 private void SetupAccelorometer()
 {
     m_accelerometer = Accelerometer.GetDefault();
     if (m_accelerometer != null)
     {
         m_accelerometer.ReadingChanged += (s, e) => Dispatcher.BeginInvoke(() =>
         {
             var reading  = m_accelerometer.GetCurrentReading();
             m_accReading = reading;
             m_angle      = Math.Atan2(-reading.AccelerationX, reading.AccelerationY) * 180.0 / Math.PI;
             Microsoft.Phone.Controls.PageOrientation orientation = (App.Current.RootVisual as PhoneApplicationFrame).Orientation;
             if (!OrientationIsLandscape())
             {
                 landscapeMessageBorder.Visibility = Visibility.Visible;
             }
             else
             {
                 landscapeMessageBorder.Visibility = Visibility.Collapsed;
             }
         });
     }
 }
Esempio n. 26
0
        /// <summary>
        /// This is the dispatcher callback.
        /// Used to diplay real time time accelerometer readings in the 3 textblocks on Page SendTextMessage.xaml
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void DisplayCurrentReading(object sender, object args)
        {
            RoutedEventArgs      temp    = null;
            AccelerometerReading reading = _accelerometer.GetCurrentReading();

            if (reading != null)
            {
                acc_x = reading.AccelerationX;
                acc_y = reading.AccelerationY;
                acc_z = reading.AccelerationZ;
                ScenarioOutput_X.Text = String.Format("{0,5:0.00}", reading.AccelerationX);
                ScenarioOutput_Y.Text = String.Format("{0,5:0.00}", reading.AccelerationY);
                ScenarioOutput_Z.Text = String.Format("{0,5:0.00}", reading.AccelerationZ);

                // Critical Step. Any component of acceleration crossing the precalculated limit of 39.2 will trigger
                // the clicking of the StartApp button with the parameter HighAccEvent set as true.
                if (acc_x > 39.2 || acc_y > 39.2 || acc_z > 39.2)
                {
                    HighAccEvent = true;
                    Send_Click(sender, temp);
                }
            }
        }
Esempio n. 27
0
 private void A_Changed(Accelerometer sender, AccelerometerReadingChangedEventArgs args)
 {
     calcDirection(sender.GetCurrentReading());
 }
Esempio n. 28
0
        void OnCompositionTargetRendering(object sender, object args)
        {
            AccelerometerReading reading = accelerometer.GetCurrentReading();

            if (reading == null)
            {
                return;
            }

            // Get elapsed time
            TimeSpan timeSpan       = (args as RenderingEventArgs).RenderingTime;
            double   elapsedSeconds = (timeSpan - this.timeSpan).TotalSeconds;

            this.timeSpan = timeSpan;

            // Convert accelerometer reading to display coordinates
            double x = reading.AccelerationX;
            double y = -reading.AccelerationY;

            // Get current X-Y acceleration and smooth it
            acceleration = 0.5 * (acceleration + new Vector2(x, y));

            // Calculate new velocity and position
            ballVelocity += GRAVITY * acceleration * elapsedSeconds;
            ballPosition += ballVelocity * elapsedSeconds;

            // Check for bouncing off edge
            bool needAnotherLoop = true;

            while (needAnotherLoop)
            {
                needAnotherLoop = false;

                if (ballPosition.X - BALL_RADIUS < 0)
                {
                    ballPosition    = new Vector2(-ballPosition.X + 2 * BALL_RADIUS, ballPosition.Y);
                    ballVelocity    = new Vector2(BOUNCE * ballVelocity.X, ballVelocity.Y);
                    needAnotherLoop = true;
                }
                else if (ballPosition.X + BALL_RADIUS > this.ActualWidth)
                {
                    ballPosition = new Vector2(-ballPosition.X + 2 * (this.ActualWidth - BALL_RADIUS),
                                               ballPosition.Y);
                    ballVelocity    = new Vector2(BOUNCE * ballVelocity.X, ballVelocity.Y);
                    needAnotherLoop = true;
                }
                else if (ballPosition.Y - BALL_RADIUS < 0)
                {
                    ballPosition    = new Vector2(ballPosition.X, -ballPosition.Y + 2 * BALL_RADIUS);
                    ballVelocity    = new Vector2(ballVelocity.X, BOUNCE * ballVelocity.Y);
                    needAnotherLoop = true;
                }
                else if (ballPosition.Y + BALL_RADIUS > this.ActualHeight)
                {
                    ballPosition = new Vector2(ballPosition.X,
                                               -ballPosition.Y + 2 * (this.ActualHeight - BALL_RADIUS));
                    ballVelocity    = new Vector2(ballVelocity.X, BOUNCE * ballVelocity.Y);
                    needAnotherLoop = true;
                }
            }
            ball.Center = new Point(ballPosition.X, ballPosition.Y);
        }