;******************************************************************************
;    ECE331 Lab 3 Part 1 
;    File: sqwave.asm (by KEH) 
;    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  #$3F00             ; Initialize program stack pointer just below UBUG12 stack.
  ;****Initialize clock generator and PLL for 24 MHz internal bus clock***********
  ;This initialization is performed by the serial debugger UBUG12, but it is not 
  ;performed when a user program is run by itself (out of RESET without the serial debugger
  ;In that case, the internal clock defaults to 16/2 = 8 MHz.  That is why I have included this 
  ;code in this program... since we want the delay routine and the serial port baud rate to remain 
  ;the same whether we are running under the debugger or without it!
  ;
  ;NOTE: This PLL initialization section may NOT be single stepped through using the serial debugger, 
  ;      since the bus clock changes, and thus so does the serial port baud rate change 
  ;      as the PLL is disconnected from the system.
  ;
	          bclr	CLKSEL,$80        	;disconnect PLL from system
	          bset	PLLCTL,$40       	  ;turn on PLL

	          movb	#2,SYNR     	      ;set PLL multiplier 
	          movb	#1,REFDV   	        ;set PLL divider
	          ;PLLCLK = OSCCLK*(SYNR+1)/(REFDV+1)= 16MHz *(2+1)/(1+1) = 24MHz
	          nop			;NOP delays put here to allow time for  	          	
            nop			;CRGFLG flag register to become valid.
wt_PLL_Lock:	
	          brclr	CRGFLG,8,wt_PLL_Lock ;Wait for PLL to lock	  
	          bset	CLKSEL,$80      	   ;Connect PLL into system
  ;*********End of PLL initialization. Now module clk = 24 MHz!
  ;*******************************************************************************
            movb #1,DDRM            ; Make PM0 an output.
            ldy  #7500              ; Note that 7500*666.667 ns = 5 ms delay time
next_cycle:	bset PTM,1              ; Set PM0 high
          	jsr wait_y_667ns        ; Delay for 5 ms		
						bclr PTM,1              ; Set PM0 low
            jsr wait_y_667ns        ; Delay for 5 ms
						bra next_cycle          ; go back to create next cycle of 100 Hz sq wave
wait_y_667ns: 
            ..............
            put your code here!
            ..............
            rts
  		        ORG       $FFFE
            	fdb  sqwave             ; Initialize Reset Vector