Timer
The Timer Resolution test application requests user input for timer interval and number of intervals to test. It displays the start and end times, as well as the times for intermediate intervals. The difference between start and end times are calculated, and compared with the theoretical value to display the error.
The TimeSpan structure is used in the calculations of time differences.
' Programme to verify resolution of the timer ticks.
' modified version of posted solution by PC 2004-01-01
Dim count As Integer = 0
Dim strNow As String
Dim m_intNInt As Integer
Dim ts1 As TimeSpan, ts2 As TimeSpan
Dim dt1 As DateTime, dt2 As DateTime
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
' determine current time
dt2 = Date.Now
' convert to string
strNow = String.Format("{0:hh':'mm':'ss'.'fff}", dt2)
If count = 0 Then
' save start time in string and in TimeSpan
TextBox1.Text = strNow
dt1 = dt2
End If
' display current time
ListBox1.Items.Add(strNow)
count += 1
If count > m_intNInt Then 'end of test
dt2 = Date.Now ' dt2=end time
TextBox2.Text = strNow
Timer1.Enabled = False ' stop clock
count = 0 ' reset count for further tests
Button1.Text = "Execute" ' reset button display
ts1 = dt2.Subtract(dt1) 'calculate time diff.
Label3.Text = "Time Difference=" & ts1.ToString
' calculate and display error
ts2 = TimeSpan.FromMilliseconds(Timer1.Interval * m_intNInt)
Label3.Text &= vbCrLf & " Error=" & ts2.Subtract(ts1).ToString
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
' validate time interval
Timer1.Interval = Val(TextBox3.Text)
If Timer1.Interval < 10 Or Timer1.Interval > 5000 Then
MsgBox("Please keep interval between 10 and 5000 ms")
End If
' validate total duration
m_intNInt = Val(TextBox4.Text)
Dim MaxDuration As Integer = 3 ' in minutes
If Timer1.Interval * m_intNInt / 1000 > MaxDuration * 60 Then
MsgBox("Please keep total duration to less than " & MaxDuration & " minutes")
End If
' reset button function
Button1.Text = "Please Wait..."
Button1.Refresh()
' reset displays
TextBox1.Text = ""
TextBox2.Text = ""
Label3.Text = ""
ListBox1.Items.Clear()
' enable timer
Timer1.Enabled = True
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' turn off timer
Timer1.Enabled = False
End Sub
Project Files updated 2004-01-01