### External Links

Creative Science Centre

## Library_timers

// #include "http://www.byvac.com//mBlib/flb/Library/2016/lib_tmr.bas"

## Timer

Constants

TIMER1 ** This timer from 2.08/76 on is used for scheduling (tasks)
TIMER2
TIMER3
TIMER4
TIMER5

TIMER23 - This is the timer 2 and 3 combination - up to 214 seconds
TIMER45 - This is the timer 4 and 5 combination - up to 214 seconds

A timer has three main parameters, the configuration that is set by timer_init(), the value of the current timer which when enabled is counting up, refered to in the data sheet as TMR register. This is controlled by tmr_clr() and tmr_get() and also the count limit, refered to in the data sheet as PR.

• tmr_init(*tmr(),prescale,limit) Initialises and starts timer 
• tmr_stop(*tmr())
• tmr_start(*tmr())
• tmr_get(*tmr()) Gets the count value of the timer (register TMRn)
• tmr_clr(*tmr())  Clears TMR - restes the timer back to 0
• tmr_limit(*tmr(),limit) Sets register PRn 

tmr_init(*timer(),prescale,limit) 

A timer can be specified by these two values. When the limit is reached the TMR register resets and starts counting up again from zero. Also a flag is set that can be either read or used by the interrupt system.

Calculate period for pre-scale assuming 40MHz perif clock
prescale             counts / ms      1 second   *32 bits needed  Timer 1 pre
256 (7) =  6.4 us    156.25         39063 (250mS)                    (3)
64   (6) =  1.6 us    625             625000   *                           (2)
32   (5) =  0.8 us    1250           1250000  *
16   (4) =  0.4 us    2500           2500000  *
8    (3) =  0.2 us    5000            5000000  *                          (1)
4    (2) =  0.1 us    10000          10000000 *
2    (1) =  0.05 us   20000         20000000 *
1    (0) =  0.025us   40000        40000000 *                          (0)

The table gives the pre-scale value (in brackets) that can be used for the given counts per mS, timer 1 has different pre-scale values. NOTE: any value over 0xffff (65,635) requires a 32 bit combination timer.

tmr_limit(*tmr(),limit) 

This will simply set the PRn resister to some other value from that which was set using the tmr_init() function.

### Timer Interrupts

ir_set(*interrupt(), pri,function_name\$)

This is the function that will associate a timer interrupt with a user defined function:

*interrupt() is TIMERn
pri is the priority 0 to 7 but 3 should be used
function_name\$ is the name of a user defined function, see the example

Example: Make hello world print out every 10 seconds

1) create a function to be called

function hello()
print "\nHello world"
endf

2) Set the timer to interrupt every 10 seconds, this will need a 32 bit timer

tmr_init(*TIMER23(),7,1562500)

3) create an entry into the interrupt table

ir_set(*TIMER23(),3,"hello")

The interrupt beigins imediately and will cause "hello World" to be output every 10 seconds. Note just the "hello" is used to specify the function.