;TimerWait demonstrations implementation
;2/16/2012 4:17:40 PM

DDRP    equ  $025A  ;Port P Data Direction Register
PTP     equ  $0258  ;Port P I/O Register
TSCR1   equ  $0046  ;Timer Control Register 1
TSCR2   equ  $004D  ;Timer Control Register 2
TCNT    equ  $0044  ;Count Register

        org  $2000  ;Start of RAM

start   rmb  2
delay   rmb  2

        org  $4000  ;Start of ROM
****Timer_Init**********
* Initialize Timer
* Input: none
* Outputs: none
* error: none
Timer_Init  
      movb #$80,TSCR1   enable TCNT
      movb #$03,TSCR2  ;1us in RUN mode
      rts

;***Timer_Wait**********
; Time delay function
; Input: RegD time to wait (1us)
; Outputs: none
; error: input must be less than 60000
;destroys D
Timer_Wait  
      std  delay      ;time to wait
      movw TCNT,start ;TCNT at start
Wloop ldd  TCNT       ;now 
      subd start      ;soFar=TCNT-Start
      cpd  delay      
Wchk  blo  Wloop      ;loop if soFar<delay
      rts

main  lds  #$4000
      bset DDRP,#$80  ;PTP7 is output
      bsr  Timer_Init
      cli             ;so debugger on real board works
loop  ldaa PTP
      eora #$80   ;LED toggle
      staa PTP
      ldd  #1000   ; 1ms
      jsr  Timer_Wait
      bra  loop
      org  $FFFE
      fdb  main