        org     0000h


	$MOD51GB

;Pulse width signals
PWM_MOT         EQU     R0
PWM_STR         EQU     R1

;Timer counter
CompCount      EQU     R2

;Motor Direction
STP_GO          EQU     P5.1
FOR_REV         EQU     P5.0

;Speeds
FWD_LO          EQU     0C0H
FWD_MED         EQU     0B0H
FWD_HI          EQU     0B0H
REV_LO          EQU     090H

;Steering Directions
Straight        EQU     03fH
Full_Left       EQU     030H
Half_Left       EQU     037H
Qtr_Left        EQU     03AH
Full_Right      EQU     04DH
Half_Right      EQU     045H
Qtr_Right       EQU     042H

;Sonar ranges
Sonar_15        EQU     245
Sonar_12        EQU     208
Sonar_9         EQU     155
Sonar_6         EQU     103
Sonar_3         EQU     51
Sonar_1         EQU     26

;IR Values
Threshold       EQU     100
CounterFlag     EQU     P5.7
Right           EQU     P5.6
Left            EQU     P5.5
Reverse         EQU     P5.4
Stop            EQU     P5.3




        org     00h

T2_ISR: push    Acc
        push    PSW
        push    07
        push    06
        push    05
        push    04
        push    03
        push    02
        push    01
        push    00

        clr     TF2             ;Clear the T2 interrupt flag
        clr     TR2             ;Stop the timer
        mov     TH2,#0B7h       ;Load the timer with the value
        mov     TL2,#0CBh       ;needed for a 10msec interval
        setb    TR2             ;turn timer back on
        jnb     CounterFlag,end_isr
        inc     CompCount       ;Increment the process counter
        clr     c
        mov     A,CompCount
        subb    A,#200
        jc      end_isr
        jnb     Right,isr1
        mov     CCAP1H,Straight
        mov     CompCount,#0
        clr     Right
        clr     CounterFlag
        jmp     end_isr

isr1:   jnb     Left,isr2
        mov     CCAP1H,Straight
        mov     CompCount,#0
        clr     Left
        clr     CounterFlag
        jmp     end_isr

isr2:   jnb     Reverse,end_isr
        clr     STP_GO           ;stop motor
        clr     FOR_REV          ;place in forward
        mov     PWM_STR,#Straight ;center wheels
        mov     CCAP1H,PWM_STR    ;

        mov     PWM_MOT,#FWD_LO  ;set motor for 1/8 speed
        mov     CCAP2h,PWM_MOT
        clr     CounterFlag
        clr     Reverse
        mov     CompCount,#0

        setb    STP_GO           ;start motor
end_isr:
        pop     00
        pop     01
        pop     02
        pop     03
        pop     04
        pop     05
        pop     06
        pop     07
        pop     PSW
        pop     Acc
        reti

	end
