; ECE331 Lab 4 (KEH)
; BLINKY.ASM - Demonstrates simultaneous operation of a non-interrupt driven 
; main program that flashes an LED (PT7) on and off at an approximate 1-second rate 
; and a precisely timed 500 Hz square wave (PT6) generating program using Timer Channel 6 
; as an output compare register.
;
            XDEF BLINKY        
            ABSENTRY BLINKY   
            INCLUDE 'mc9s12c128.inc'
            ORG $4000
BLINKY:     lds #$1000	      ;Initialize Stack to top of RAM.
            movb  #$80,DDRT   ;Make PT7 a digital output.
            movb  #3,TSCR2    ;Set prescaler bits to 3 so TCNT increments every 
                              ;8/2MHz = 4 microseconds.
            movb  #$80,TSCR1  ;Enable Timer TCNT to begin counting
            movb  #$40,TIE    ;Locally Enable TC6 interrupts
            movb  #$40,TIOS   ;Make TC6 an Output Compare register
            movb  #$10,TCTL1  ;Make TC6 pin toggle when output compare event occurs.
            ldd   TCNTHi      ;Load TCNT into register D
            addd  #250        ;Add 250 TCNT increments to it.  Note 250*4us = 1 ms.
            std   TC6Hi       ;Schedule next output compare interrupt to occur in 1 ms
            movb  #$40,TFLG1  ;Make sure TC6 interrupt flag is cleared
            cli		            ;globally enable interrupts
blinkagain: bclr  PTT,$80			;Turn off LED on PT7
            bsr   onesecdelay
						bset  PTT,$80     ;Turn ON LED on PT7
						bsr   onesecdelay
						bra   blinkagain
;*********Here ends the main program "BLINKY"

onesecdelay:pshx	            ;Software timing loop delay routine -- 
                              ;Delays approx 1 second,depending upon how 
                              ;much time is taken away to process interrupts.
            pshy
            ldx   #16
outerloop:  ldy   #$3fff
innerloop:  dey
            bne   innerloop
            dex
            bne   outerloop
            puly
            pulx
            rts
                                 
TOC6ISR:    
            ldd   TC6Hi      ;We could load TCNTHi,but loading TC6Hi is more accurate
            addd  #250       ;Schedule another interrupt in exactly 1 ms from 
                             ;when the previous interrupt occurred.
            std   TC6Hi
            movb  #$40,TFLG1   ;Relax the TC6 interrupt flag before returning.
            rti
            

;**************************************************************
;*    Initialize Reset Vector and TC6 Interrupt Vector        *
;**************************************************************
  ORG $FFFE
  fdb     BLINKY     ;Make reset vector point to entry point of BLINKY program
  ORG $FFE2
  fdb     TOC6ISR    ;Make TC6 interrupt vector point to TC6 interrupt rtn