; ECE331 Lab 4 (KEH, August 2004)
; 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 'mc9s12c32.inc'
            ORG $4000
BLINKY:     lds #$3f00
            movb  #$80,DDRT   ;Make PT7 a digital output.
            movb  #5,TSCR2    ;Set prescaler bits to 5 so TCNT increments every 
                              ;32/24MHz = 1.333 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  #750        ;Add 750 TCNT increments to it.  Note 750*1.33us = 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   #46
outerloop:  ldy   #$ffff
innerloop:  dey
            bne   innerloop
            dex
            bne   outerloop
            puly
            pulx
            rts
                                 
TOC6ISR:    
            ldd   TCNTHi
            addd  #750        ;Schedule another interrupt in 1 ms from now
            std   TC6Hi
            movb  #$40,TFLG1   ;Relax the TC6 interrupt flag
            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