Reputation: 61
I need a way to finding out when the time from 0 ends up as 4 secs.
My code is as follows:
I have a global variable called weightdelaycount, which is incremented every 1000 intervals.
Private Sub Timer_weightcheck_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer_weightcheck.Tick
weightdelaycount = weightdelaycount + 1
End Sub
Now I have the do while loop that runs infinitely and only stops depending on two conditions. Either the weightchange = True or if the clock = 4 secs.
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
weightdelaycount = 0
Timer_weightcheck.Enabled = True
Do While 1
If (weightchange() = True ) Then
Timer_weightcheck.Enabled = False
Exit Do
End If
If (weightdelaycount = 4) Then
Timer_weightcheck.Enabled = False
Exit Do
End If
Loop
MessageBox.Show(weightdelaycount)
End Sub
From the routine above you see that I'm using exit Do to exit the loop if the two conditions are met. The problem is that if the weightchange() is not True and 4 seconds passed the systems doesn't stop. I can put a delay in there and then it works, but I need to be accurate with the values that I get for the weight from a scale. If I put a delay, then the values will not be accurate. Is there a way to solve this?
Thank you in advance
Upvotes: 0
Views: 2305
Reputation: 4439
Instead of using a timer, you could use a stopwatch. This code will loop until 4000ms after the stopwatch has started. You'll never get it to stop exactly on 4000ms because of the time it takes to run through the the Do..Loop(minimal really), but I presume a couple of ms after is close enough.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim weightdelaycount = 0
Dim timer As New Stopwatch
timer.Start()
Do
If (weightchange() = True) Then
timer.Stop()
Exit Do
End If
Loop Until timer.ElapsedMilliseconds > 4000
timer.Stop()
MessageBox.Show(timer.ElapsedMilliseconds)
End Sub
Upvotes: 3