;******************************************************************************
;    ECE331 Lab 3 Part 1 
;    File: sqwave.asm (by KEH) August 2004 
;    Square Wave Generating Program that calls "wait_y_667ns" subroutine
;    to generate a 100 Hz square wave on pin PM0 that is 5 ms high and 5 ms low.
;******************************************************************************
            XDEF sqwave             ; Export 'program entry point' symbol
  
            ABSENTRY sqwave         ; For absolute assembly: mark this as application entry point
            INCLUDE 'mc9s12c32.inc'	; Include 9S12C32 register symbol definitions.
            ORG $4000
sqwave:     lds  #$1000             ; Initialize program stack pointer to point to one location above
                                    ; end of RAM block ($800 - $FFF)
            movb #1,DDRM            ; Make PM0 an output.
            ldy  #2500              ; Note that 2500*2 us = 5 ms delay time
next_cycle:	bset PTM,1              ; Set PM0 high
          	jsr wait_y_2us        ; Delay for 5 ms		
						bclr PTM,1              ; Set PM0 low
            jsr wait_y_2us        ; Delay for 5 ms
						bra next_cycle          ; go back to create next cycle of 100 Hz sq wave
wait_y_2us: 
            pshd
            bset TSCR1,$80          ; Turn on 16-bit timer (TEN = 1)
            bset TSCR2,%00000100    ;
            bclr TSCR2,%00000011    ; Set prescaler to divide internal
                                    ; bus clock by 16, so TCNT increments
                                    ; once every 16/24 = 2/3 microsec.
            bset TIOS,%00000100     ; Configure Timer Channel #2 as an "output compare" reg
            bclr TIE,  %00000100    ; Disable interrupts on Timer Channel 2
            tfr y,d
            addd TCNTHi
            std  TC2Hi              ; Schedule Output Compare Event in 2/3 micosec
            movb #4,TFLG1           ; Clear channel 2 output compare flag
wtoc2:      brclr TFLG1,%00000100,wtoc2 ;Wait here till output compare occurs
            puld
            rts
  		        ORG       $FFFE
            	fdb  sqwave             ; Initialize Reset Vector