;Timekeeping Example, using Timer 0 with simple polling ;http://www.pjrc.com/tech/8051/board4/timers.html ;This examples demonstrates how to use Timer 0 to keep track ;of time. Timer 0 is used in mode 0, which produces 225 ;overflows per second (22.1184 MHz crystal). .equ cout, 0x0030 ;Send Acc to serial port .equ cin, 0x0032 ;Get Acc from serial port .equ phex, 0x0034 ;Print Hex value of Acc .equ pstr, 0x0038 ;Print string pointed to by DPTR, .equ esc, 0x003E ;Check for ESC key .equ newline, 0x0048 ;print CR/LF (13 and 10) .org 0x2000 begin: mov r7, #0 ;zero hours, minutes, seconds mov r6, #0 mov r5, #0 clr tr0 ;make sure timer 0 is stopped clr tf0 ;clear the overflow flag anl tmod, #0xF0 ;set to mode 0 (without touching timer 1) mov th0, #0 ;clear the timer 0 value mov tl0, #0 mov r2, #225 ;start overflow countdown (1 second) mov dptr, #msg_begin lcall pstr setb tr0 ;start the timing lcall print_time timekeeping_loop: lcall esc jc abort jnb tf0, timekeeping_loop ;did timer 0 overflow? clr tf0 ;reset overflow flag djnz r2, timekeeping_loop ;is this 225 overflows (exactly 1 second) lcall inc_time lcall print_time mov r2, #225 ;reset countdown for another second sjmp timekeeping_loop abort: mov dptr, #msg_end lcall pstr lcall cin ljmp 0 inc_time: inc r5 ;increment seconds cjne r5, #60, inc_time_end mov r5, #0 inc r6 ;increment minutes cjne r6, #60, inc_time_end mov r6, #0 inc r7 ;increment hours cjne r7, #24, inc_time_end mov r7, #0 inc_time_end: ret print_time: mov a, r7 ;hours lcall print_2digit_int mov a, #':' lcall cout mov a, r6 ;minutes lcall print_2digit_int mov a, #':' lcall cout mov a, r5 ;seconds lcall print_2digit_int lcall newline ret print_2digit_int: mov b, #10 ;divide by 10... div ab add a, #'0' ;quotient is tens digit lcall cout mov a, b ;remainder is ones digit add a, #'0' lcall cout ret msg_begin: .db 13,10,13,10,13,10 .db "Timekeeping Example (Polling)",13,10 .db "Press ESC to stop...",13,10,13,10,0 msg_end: .db 13,10,13,10,"Stopped. Press a key to reboot",0