Using "time" variable on M2 parts to implement muliple timed action triggers

lbenson

Senior Member
Using "time" variable on M2 parts to implement muliple timed action triggers

My preference in using the "time" variable is to wrap it every half day, after 43200 seconds (60 seconds times 60 minutes times 12 hours), and use a bit variable as an am/pm indicator (understanding that you don't have real-world accuracy).

When you decide that an action must occur in the future, you set a word variable to "time" plus how many seconds in the future you want the action to be taken. When "time" is greater than that variable, you perform the action. If "time" becomes > 43199, you adjust the variables and reset "time" to 0.

so as a structure for timing two actions:
Code:
#picaxe 14M2 ' or other M2 picaxe

symbol wEventTime1 = s_w1 ' 0 when off, otherwise number > 'time'
symbol wEventTime2 = s_w2 ' 0 when off
symbol bAMPM = bit0
main:
  do
    if time > 43199 then
      if wEventTime1 > 43199 then
        wEventTime1 = wEventTime1 - 43199 min 1 ' don't allow 0--OFF indicator
      endif
      if wEventTime2 > 43199 then
        wEventTime2 = wEventTime2 - 43199 min 1 ' don't allow 0--OFF indicator
      endif
    endif
    time = 0
    if bAMPM = 0 then : bAMPM = 1 : else bAMPM = 0 : endif ' toggle bit

' your code testing to see if timer has expired
    if wEventTime1 > 0 and timer > wEventTime1 then
      ' do something
      wEventTime1 = 0 ' reset event timer
    endif
    if wEventTime2 > 0 and timer > wEventTime2 then
      ' do something
      wEventTime2 = 0 ' reset event timer
    endif

' your code determining that something should be done later
    if [someevent] then
      wEventTime1 = 60 * 2 + time ' do something in 2 minutes
    endif
    if [anotherevent] then
      wEventTime2 = 60 * 60 + time ' do something in an hour
    endif
'   the rest of your code
  loop
This assumes that the main loop cycles without being blocked--several times a second or at least often enough that you don't encounter timing problems. Also, your "time + n" is never going to overflow (be > 65535).
 
Top