;EE319K example from class 3/1/2012
; 9S12C32
PTAD     equ $0270  ; Port AD I/O Register
DDRAD    equ $0272  ; Port AD Data Direction Register
ATDDIEN  equ $008D  ; ATD Input Enable Mask Register
DDRM     equ $0252  ; Port M Data Direction Register
PTM      equ $0250  ; Port M I/O Register
DDRT     equ $0242  ; Port T Data Direction Register
PTT      equ $0240  ; Port T I/O Register
TCNT     equ $0044  ; Timer Count Register
TSCR1    equ $0046  ; Timer System Control Register1
TSCR2    equ $004D  ; Timer System Control Register 2 
      org  $3800    ; Globals go in 2K Ram
delay ds.w 1        ; number of cycles to wait
start ds.w 1        ; TCNT value at the start of wait
Pt    rmb  2  ;pointer to current state
     org  $4000
out  equ  0    ;8-bit output
wait equ  1    ;time to wait, 32us units
next equ  3    ;4 pointers to next state
S5   fcb $05   ;4-bit output
     fdb 4000
     fdb S5,S9,S6,S5 ;next for each in
S6   fcb $06
     fdb 4000
     fdb S6,S5,S10,S6 
S10  fcb $0A
     fdb 4000
     fdb S10,S6,S9,S10 
S9   fcb $09
     fdb 4000
     fdb S9,S10,S5,S9
* ROM program
Main lds  #$4000
     bsr  Timer_Init   ; activate TCNT 
     bset DDRT,#$03    ; PT1 PT0 output to LEDs
     bset ATDDIEN,#$C0 ; PAD6,7 digital
     bclr DDRAD,#$C0   ; PAD6,7 input
     bset DDRM,#$0F    ; PM3-0 output
     movb #$05,PTM     ; initial output    
     movw #S5,Pt       ; initial state
     cli               ; allow debugger
loop ldx  Pt
     movb out,X,PTM   ; step motor    
     ldd  wait,X 
     bsr  Timer_Wait  ; wait specified time
     ldaa PTAD        ; read inputs (negative logic)
     eora #$C0        ; positive logic
     anda #$C0        ; just CCW,CW
                      ; 0,40,80,C0
     lsra             ; 0,20,40,60
     lsra             ; 0,10,20,30
     lsra             ; 0,08,10,18
     lsra             ; 0,04,08,0C
     lsra             ; 0,02,04,06
     leax next,X      ; list of pointers
     ldx  A,X         ; next depends on in
     stx  Pt
     ldaa PTT
     eora #$01
     staa PTT         ; heart beat
     bra  loop

****Timer_Init**********
* Initialize Timer
* Input: none
* Outputs: none
* error: none
Timer_Init  
      movb #$80,TSCR1   enable TCNT
      movb #$04,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
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

  org $FFFE
  fdb Main