Keeping track of time using interrupts

The following Basic18 source will keep track of elapsed hours, minutes, and seconds

 

' Code based on a 4MHz system clock

include      ' For chip specific definitions

option explicit

dim time as fixed
dim seconds as ubyte, minutes as ubyte, hours as ubyte

sub main()

  ' init variables
  seconds=0
  minutes=0
  hours=0
  time=0.0

  ' Init Timer1 1:1 Interrupt enabled
  T1CON=1 ' 1:1
  TMR1IF=0 ' clear the interrupt flag
  TMR1IE=1: GIE=1: PEIE=1 ' enable the interrupt


  ' At this point the interrupt routine will automatically keep the
  ' variables hours, minutes, and seconds up to date  


end sub


' Interrupt code
sub isr() inthigh

    ' check for a timer 1 interrupt
    if TMR1IF=1 then
       TMR1IF=0  ' clear the timer flag
       time=time+0.065536 ' add 65.536mS to the time keeping variable

       ' Has a second passed yet?
       if time>=1.0 then
          time=time-1.0   ' if so then adjust the variables
          seconds=seconds+1
          if seconds>59 then
             seconds=0: minutes=minutes+1
             if minutes>59 then
                minutes=0: hours=hours+1
             end if
          end if
       end if

    end if

end sub