PDA

View Full Version : Timer with TMR0



piombazzo
- 19th January 2006, 08:49
Help me,
i want create a counter in 1 sec with the TMR0 and interrupt, the pic is 16f877a osc 20Mhz.
I have utilized the formule Time = Mhz * periode * (Tmr0-N) * prescaler
Time = (20 * 50 *(256)*64)/1M= 16384*61 =999.424
but it not functional.
Help Me
SOS.
Aiutoooooo

robert0
- 19th January 2006, 09:40
Look here, even if on a different pic than yours:

http://www.microengineeringlabs.com/resources/samples/x4/PBP/CLOCKX4.BAS

bye ( se sei italiano ciaooo)

roberto

piombazzo
- 19th January 2006, 10:19
Hy Robert (ciao si sono Italiano )
thank you for answer
but the osc in the example is 4 Mhz,
i use a osc to 20 Mhz.
Help Me.

Bruce
- 19th January 2006, 17:26
@ DEVICE LVP_OFF,HS_OSC
DEFINE OSC 20
DEFINE INTHAND TMRint

'Variables for saving state in interrupt handler
wsave VAR BYTE $70 system ' Saves W
ssave VAR BYTE bank0 system ' Saves STATUS
psave VAR BYTE bank0 system ' Saves PCLATH
fsave VAR BYTE bank0 system ' Saves FSR

TMR0_Ticks VAR BYTE system

TMR0 = 96

GoTo Init

Asm
TMRint
; Uncomment the following if the device has less than 2k of code space
; movwf wsave ; Save W
; swapf STATUS, W ; Swap STATUS to W (swap avoids changing STATUS)
; clrf STATUS ; Clear STATUS
; movwf ssave ; Save swapped STATUS
; movf PCLATH, W ; Move PCLATH to W
; movwf psave ; Save PCLATH

; Increment ticks, reload, clr int flags
;------------------------------------------------------------------------------
incf TMR0_Ticks,f ; increment overflow ticks
movlw 96 ; 256-96=160. 160x200nSx256=8.192mS. 8.192mSx122=0.999mS= ~1S
movwf TMR0 ; reload
bcf INTCON,2 ; clear TMR0 int flag
;----------------------------------------------------------------------------

movf fsave, W ; retrieve FSR value
movwf FSR ; Restore FSR
movf psave, W ; Retrieve PCLATH value
movwf PCLATH ; Restore PCLATH
swapf ssave, W ; (swap to avoid changing STATUS)
movwf STATUS ; Restore STATUS
swapf wsave, F ; Swap the stored W value
swapf wsave, W ; Restore it to W (swap to avoid changing STATUS)
retfie ; Return from the interrupt
EndAsm

Init:
PORTD = 0
TRISD = 0
OPTION_REG = %00000111 ' 1:256 prescaler to TMR0
INTCON = %11100000 ' Enable TIMR0 interrupts

Main:
IF TMR0_Ticks >= 122 THEN
TMR0_Ticks = 0
PORTD.0 = PORTD.0 ^ 1 ' ~1 second pulse on RD0
ENDIF
GOTO Main

End
Timer1 would be better, but this should get you started.

piombazzo
- 20th January 2006, 08:10
Thank You
Bruce.

robert0
- 20th January 2006, 09:02
I used Timer2 on a PIC16F628 for 1.5 seconds:

T2CON=%01111010 'prescaler 1:16 POSTSCALER 1:16 ,STOP TIMER2

Then start timer and in interrupt handler:

if PIR1.1=1 then
Count= Count +1
if Count =100 then
high led
endif
T2CON.2=0
PIR1.1=0 'reset flag interrupt
resume
endif

Every interrupt of timer Count is incremented....when is 100 =1,5 sec
It's easy to change to TMR0 or Timer1....and also you can change the number of count

Ciao
Roberto