; export symbols
            XDEF Theremin            ; export 'Entry' symbol
            ABSENTRY Theremin        ; for absolute assembly
            INCLUDE 'MC9S12C128.inc'
            ORG $400
            ORG $4000
const32: 
            dc.l 674716        ; allocates a 32-bit "long word" 
               
Theremin:   lds   #$1000       ; initialize the stack pointer
            movb #1,TSCR2      ; Tick rate = 2/2MHz = 1 usec
            movb #$80,TSCR1    ; Start TCNT counting
            bset TIOS,1        ; Make TC0 output compare
            bset TIE,1         ; Make TC0 interrupt on compare
            movb #1,TCTL2      ; Make PT0 toggle with each oc interrupt
            bclr DDRAD,1
            bclr ATDDIEN,1     ; Make AN0 an analog input
            bset ATDCTL2,$80   ; Power up A/D
            ldx #$ffff
wt_for_ATD_power_up:
            dex
            bne wt_for_ATD_power_up   ;Wait for A/D to power up
            movb #%00001000,ATDCTL3 
            movb #%00000001,ATDCTL4 
            
            movb #%10000000,ATDCTL5 
wt_done:    brclr ATDSTAT0,$80,wt_done
            ldd ATDDR0
            ldy #5532
            emuls
            subd const32+2
            tfr d,x
            tfr y,d
            bcc skip_adjust
            subd #1
skip_adjust:            
            subd const32
            tfr d,y
            tfr x,d
            ldx #1000
            edivs
            tfr y,d
            addd TCNT
            std TC0
            movb #1,TFLG1
            cli
idle_loop:  bra idle_loop             
            
            
tc0isr:     movb #%10000000,ATDCTL5 
wt_done1:   brclr ATDSTAT0,$80,wt_done1
            ldd ATDDR0
            ldy #5532
            emuls
            subd const32+2
            tfr d,x
            tfr y,d
            bcc skip_adjust1
            subd #1
skip_adjust1:            
            subd const32
            tfr d,y
            tfr x,d
            ldx #1000
            edivs
            tfr y,d
            addd TC0
            std TC0
            movb #1,TFLG1
            rti            
           
            ORG   $FFFE
            DC.W  Theremin           ; Reset Vector
            ORG   $FFEE
            DC.W  tc0isr