Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

StopWatch doesn't stop

I am sure there is something wrong with logic but I just can’t figure out what.
I am trying to count for how long the user is walking by using accelerometer (phone movement) and if there is no movement for 3 seconds the time should stop and if the user starts moving again the time should start again and it should add to time achieved earlier but the time does not stop after there is no movement.

 public partial class Walking : ContentPage
{
    
    private double lastX;
    private double lastHandledX;
    private TimeSpan timeForRewards;

    Stopwatch stopWatch = new Stopwatch();
    public Walking()
    {
        InitializeComponent();
        Accelerometer.ReadingChanged += Accelerometer_ReadingChanged;
        
    }

    private void Accelerometer_ReadingChanged(object sender, AccelerometerChangedEventArgs e)
    {
       
       lastX = e.Reading.Acceleration.X;
      
        acc.Text = $"X: {e.Reading.Acceleration.X}";
    }

    private bool OnTimerTriggered()
    {
        if (lastX!=lastHandledX)
        {
            stopWatch.Start();
            walks.Text = "Yay I am walking";
        }
        else
        {
            stopWatch.Stop();
            timeForRewards += stopWatch.Elapsed;
            walks.Text = $"Oh, we've stopped walking! time: {timeForRewards}";
            
        }
        lastHandledX = lastX;   
        
        return true;
    }
    void StartWalking_Clicked(object sender, EventArgs e)
    {

        if (Accelerometer.IsMonitoring)
        {
            Accelerometer.Stop();
        }
        else Accelerometer.Start(SensorSpeed.UI);

        Accelerometer.ReadingChanged += Accelerometer_ReadingChanged;
        Device.StartTimer(new TimeSpan(0, 0, 2), OnTimerTriggered);


    }
  
}

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use Stopwatch.Restart()

Stops time interval measurement, resets the elapsed time to zero, and starts measuring elapsed time.

instead of Stopwatch.Start()

Starts, or resumes, measuring elapsed time for an interval.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading