The BasicX provides a real time clock which is useful in providing for such periodic tasks as turning on a motor for the first five minutes of each hour or similar.
However the Timer() command permits one to set the time for performing a task at any value up to 86400 seconds.
For example, consider an application where a task which takes a variable period of time is performed and it is desired to perform this task periodically. In the following routine, the task is one of flashing an LED a number of times (1 to 10) which may take from 1.0 to nominally 10.5 seconds and it is desired to repeat this every 20 seconds.
The current time in elasped seconds since midnight is fetched using the Timer command. The alarm time is calculated by adding the period, in this case 20 seconds.
The task is then performed and the program then loops until the current time is greater than or equal to the alarm time. Of course, the program could be performing other chores during this looping.
A problem occurs when the alarm time exceeds 86,400 seconds. The clock will simply reach 86,399 and then roll over to zero and thus current time will never be greater than or equal to alarm time. This is handled by subtracting 86400 from the alarm time and first looping until current time is less than or equal to alarm time (when the timer rolls over) and then continuing to loop until current time is greater than or equal to alarm time.
' Periodic_2.Bas ' ' ' Copyright, Peter H. Anderson, Baltimore, MD, Oct, '99 Sub Main() Dim RollOverFlag as Byte Dim NumFlashes as Integer Dim CurrentTime as Single Dim AlarmTime as Single Call OpenSerialPort(2, 9600) ' for debugging Call PutTime(23, 59, 0.0) ' for testing roll over of timer NumFlashes = 0 CurrentTime = Timer() Do AlarmTime = CurrentTime + 20.0 ' every 20 seconds If (AlarmTime > 86400.0) then ' there was a rollover AlarmTime = AlarmTime - 86400.0 RollOverFlag = 1 Else RollOverFlag = 0 End If ' Now do the task NumFlashes = NumFlashes + 1 If (NumFlashes > 10) Then NumFlashes = 1 End If Call Flash(NumFlashes) ' now time for the duration of the 20 seconds If (RollOverFlag = 0) then Do CurrentTime = Timer() Loop Until (CurrentTime >= AlarmTime) Else Do CurrentTime = Timer() Loop Until (CurrentTime <= AlarmTime) ' wait for the timer to ' roll over Do CurrentTime = Timer() Loop Until (CurrentTime >= AlarmTime) End if CurrentTime = AlarmTime Loop End Sub Sub Flash(ByVal NumFlashes as Integer) ' Flash LED a number of times Dim N as Integer Dim str as String str = "..." Call PutStr(str) For N = 1 to NumFlashes Call PutPin(22, 0) Call Sleep(0.5) Call PutPin(22, 1) Call Sleep(0.5) Next End Sub