        $MOD51GB

        EOC     equ     P4.0
        SS      equ     P4.1
        MS      equ     P4.2
        RESET   equ     P4.3
        SCLK    equ     P4.4
        SDO     equ     P4.5
        POLL    equ     P4.6
        POW     equ     P4.7

        CompCount  equ  R7
        DataByte   equ  R4

	org 	8000h
        jmp     8200h

        org     802bh
        jmp     T2_ISR
                
        org     8100h
        db      0,0
        org     8200h
        call    Comp_Init       ;Initialize the compass
        call    Print
        db      'The compass is initialized\n',0,
        call    T2_Init         ;Initialize T2
        call    Print
        db      'Timer 2 is initialized\n',0,

        setb    MS
ComRd:  call    Print
        db      '\n     Press the g key to get a compass heading\n',0,
start:  call    cin
        cjne    A,#'g',start

        setb    ET2             ;enable Timer 2 interrupt
        setb    EA              ;enable interrupts

wait:   jmp     wait

Comp_Init:
        ;set all the bits on the compass
        setb    POW             ;turn power off
        setb    POLL            ;set the poll bit
        setb    SS              ;set the slave select bit
        setb    RESET           ;set the NOT Reset line
        setb    SCLK            ;set the shift clock
        setb    SDO             ;setting SDO will set that pin on the
                                ;8051 as an input
        setb    EOC             ;same for EOC

        clr     POW             ;turn power on

        ;Initialize the counter for the compass process controller
        mov     CompCount,#0
        clr     RESET           ;reset compass
        call    Delay10         ;wait 10msecs
        setb    RESET           ;clear reset
        call    lngDelay        ;wait .5secs


        ret

T2_Init:
        ;load the timer to run the compass
        clr     TR2             ;turn Timer 2 off
        mov     TH2,#0B7h       ;load the T2 high byte
        mov     TL2,#0CBh       ;load the T2 low byte
        setb    TR2             ;turn Timer 2 on
        ret

T2_ISR:
        $INCLUDE(T2_ISR.INC)

clkdelay: mov   R0,#073h
clk:	djnz	R0,clk
	ret

delay10: mov    R0,#025h
delay:	mov	R1,#0FFh
delay1:	djnz	R1, delay1		;wait >10 msec
	djnz	R0, delay
	ret


lngDelay: mov   R0,#00Ah
delay2:	mov	R1,#035h
delay3:	mov	R2,#0FFh
delay4:	djnz	R2, delay4		;wait >500msec
	djnz	R1, delay3
	djnz	R0, delay2
	ret

cin:    
        $INCLUDE(cin.inc)
        
cout:   
        $INCLUDE(cout.inc)

PRINT:
        $INCLUDE(Print.inc)

pint16u:
        $INCLUDE(pint16u.inc)

        END
