Here’s the minal code to make a timer in the PICBasic programming language. All the crap code trying to explain timers on the internet is crap. Here’s all you need. This code will run an infinite loop taking exactly ‘SomeNumber’ amount of time for each loop (as long as ‘SomeNumber’ amount of time is longer than the maximum amount of time that it takes for MamaLoop to finish).

General Description of PIC timer variables used to control the timer: (you should be able to use these no matter what programming language you use):

NOTE:
when I say ‘timer value’ I mean a number representing the amount of time since the timer was started, I’m not sure what the units of this number are.

TMR1H is the timer value’s high byte
TMR1L is the timer value’s low byte
–so–
TMR1L = 0, TMR1H = 0, resets the value

T1CON.0 is the first bit of the timer configuration byte
–so–
T1CON.0=1, starts the timer
T1CON.0=0, stops the timer

Here’s the Code:

‘####################################################
SomeNumber var word
SomeNumber = 4500

T1CON.0=1 ‘start timer

‘—————————————–
MamaLoop:
TMR1L = 0 ‘Set the low part of the timer value to 0
TMR1H = 0 ‘Set the high part of the timer value to 0

‘do whatever you want in the loop
‘….blah if, then, blahblah
‘….blah if, then, blahblah
‘….blah

‘the EndLoopDelay will wait until a specified amount of time has passed since the start of the MamaLoop (when the timer value was set to 0)
EndLoopDelay:
CLEARWDT ‘clear the watchdog timer (so PIC doesn’t reset)
LTime.Highbyte=TMR1H ‘get part of the timer value
LTime.Lowbyte=TMR1L ‘get the rest of the timer value
IF LTime > SomeNumber THEN ‘if the timer value > than your number
GOTO FinishLoop
else
GOTO EndLoopDelay
endif
‘——————————————

FinishLoop:
‘do something at the end of the loop
‘then go back to restart the MamaLoop
GOTO MamaLoop

‘####################################################

By: leevonk

More: continued here