Sunday, July 20, 2008

Real Time Clock - 8051

$MOD51
HOURS EQU 07Ch ;Our HOURS variable
MINUTES EQU 07Dh ;Our MINUTES variable
SECONDS EQU 07Eh ;Our SECONDS variable
TICKS EQU 07Fh ;Our 20th of a second countdown timer
CRYSTAL EQU 11059000 ;The crystal speed
TMRCYCLE EQU 12 ;The number of crystal cycles per timer increment
TMR_SEC EQU CRYSTAL/TMRCYCLE ;The # of timer increments per second 921583
F20TH_OF_SECOND EQU TMR_SEC * .05 ;Setting the time period to be .05 * 20 = 1 sec
RESET_VALUE EQU 65536 -F20TH_OF_SECOND ;for .05 sec timer has to increment 921583*.05 = 46079 times , timer resets at 65536 , so initialize the timer value with 65536-46079


ORG 2000h ;Start assembly at 0000h
LJMP MAIN ;Jump to the main routine

ORG 001Bh ;This is where Timer 1 Interrupt Routine starts
PUSH ACC ;We'll use the accumulator, so we need to protect it
PUSH PSW ;Protect PSW flags
CLR TR1 ;Turn off timer 1 as we reset the value
MOV TH1,#HIGH RESET_VALUE ;Set the high byte of the reset value
MOV TL1,#LOW RESET_VALUE ;Set the low byte of the reset value
SETB TR1 ;Restart timer 1 now that it has been initialized
DJNZ TICKS,EXIT_RTC ;Decrement TICKS, if not yet zero we exit immediately
MOV TICKS,#20 ;Reset the ticks variable
INC SECONDS ;Increment the second varaiable
MOV A,SECONDS ;Move the seconds variable into the accumulator
CJNE A,#60,EXIT_RTC ;If we haven't counted 60 seconds, we're done.
MOV SECONDS,#0 ;Reset the seconds varaible
INC MINUTES ;Increment the number of minutes
MOV A,MINUTES ;Move the minutes variable into the accumulator
CJNE A,#60,EXIT_RTC ;If we haven't counted 60 minutes, we're done
MOV MINUTES,#0 ;Reset the minutes variable
INC HOURS ;Increment the hour variable
EXIT_RTC:
POP PSW ;Restore the PSW register
POP ACC ;Restore the accumulator
RETI ;Exit the interrupt routine

; write display function here

MAIN:
MOV TH1,#HIGH RESET_VALUE ;Initialize timer high-byte
MOV TL1,#LOW RESET_VALUE ;Initialize timer low-byte
MOV TMOD,#10h ;Set timer 1 to 16-bit mode
SETB TR1 ;Start timer 1 running
MOV HOURS,#00 ;Initialize to 0 hours
MOV MINUTES,#00 ;Initialize to 0 minutes
MOV SECONDS,#00 ;Initialize to 0 seconds
MOV TICKS,#20 ;Initialize countdown tick counter to 20
SETB EA ;Initialize interrupts
SETB ET1 ;Initialize Timer 1 interrupt
END

No comments: