PDA

View Full Version : Implement a timer without using an interrupt



coyotegd
- 26th February 2006, 06:43
I've read the posts on using timers, but I have not been able to get one to work in my situation. I would like to use a timer to turn off a LCD backlight after approximately 5 seconds without pausing program execution. I am using PORTD.6 of a 16F877A to turn the LCD backlight on. Here is what I tried:

T2CON = %01111010 ' Pre- and Post-scaler 1:16, stop timer
Counter VAR BYTE

MAIN:
if PORTB <> 255 then GOSUB UPDATE_LCD
if PIR1.1 = 1 then
Counter = Counter + 1
PIR1.1 = 0
endif
if Counter = 350 then
PORTD.6 = 0
T2CON.2 = 0
endif
GOTO MAIN

UPDATE_LCD:
PORTD.6 = 1 ' Turn on backlight
T2CON.2 = 1 ' Turn on timer
' Code to update LCD information
RETURN

Bruce
- 26th February 2006, 17:09
PR2 is is initialized to 255 on reset.

With Timer2 prescaler & postscaler set to 16, it takes 16*255*16
clock cycles before PIR1.1 is set.

At 4MHz this = 65,280uS.

65,280uS * 350 = 22.848 seconds.

If you need ~5 seconds, increment Counter up to 76.

76 * 65,280uS = roughly 4.961S + whatever program over-head you
have in the process.

P.S. You need Counter to be a "word" size if it's counting past 255,
and you should initialize your Counter variable to 0 before Main, then
clear it once it's reached your max count.

if Counter = 350 then
This will never be true since it will roll-over from 255 to 0

coyotegd
- 26th February 2006, 18:05
I am not sure why you mention "PR2 is initialized to 255 on reset". I have no idea what you are trying to tell me.

However, your explanation and advice to change my Counter trigger to 76 did the trick with the addition of resetting the Counter to 0 when I turn the timer on.

Works like a charm.

Ken

Bruce
- 26th February 2006, 18:44
When Timer2 counts up to the value in PR2, PIR1.1 is set, and Timer2 is
reset to 0. It doesn't over flow when it rolls-over from 255 to 0 like other
8-bit timers.

The time is takes for PIR1.1 to be set =;

(prescaler)*(PR2)*(postscaler)*(instruction cycle time).

Since PR2 is initialized to 255, and you're using both prescaler & postscaler
set to 16, then (assuming a 4MHz osc) 16*255*16*1uS* your Counter value
of 76 = 4.9 seconds.

Look in the Timer2 section of your data sheet for the whole story..;o}

Try placing PR2 = 127 in the startup section of your code to see the effect.