; NOTE:  THIS IS A NON-BOOTUP PROGRAM, IT DOESN'T HAVE LINES TO CLEAR THE WDT
; SINCE THAT'S BEEN TAKEN CARE OF BY THE SMALL-C MONITOR.

        $MOD51GB

PWMCNT  EQU     R2                  ; use R2 as the PMW duty cycle counter 

        ORG     8000H

        MOV     P1,#00FFH           ; IN ORDER FOR THE PWM SIGNAL TO TAKE EFFECT,
                                    ; ALL OUTPUT BITS ON PORT 1 MUST BE SET HIGH

        MOV     PWMCNT,#07FH         ; START THE PW VALUE WITH 01
        MOV     CCAP2H, PWMCNT      ; LOAD THE PWM REGISTER WITH THE PW VALUE
        CALL    PCA_INIT            ; INITIALIZE THE PWM

MAIN_LOOP:

        
        CALL    CIN                 ; WAIT FOR A KEY TO BE PRESSED
        CJNE    A,#'1',K2           ; IF KEY='1'
        INC     PWMCNT              ; INCREMENT THE PULSE WIDTH TIMER VALUE
        MOV     CCAP2H, PWMCNT      ; LOAD THE PWM REGISTER WITH THE PW VALUE
        SJMP    MAIN_LOOP

K2:     CJNE    A,#'2',K3           ; IF KEY='2'
        DEC     PWMCNT              ; DECREMENT THE PULSE WITH TIMER VALUE
        MOV     CCAP2H, PWMCNT      ; LOAD THE PWM REGISTER WITH THE PW VALUE
        SJMP    MAIN_LOOP

K3:     CJNE    A,#'3',K4           ; IF KEY='3'
        CLR     P5.1                ; TURN OFF MOTOR
        SJMP    MAIN_LOOP


K4:     CJNE    A,#'4',KQ           ; IF KEY='4'
        SETB    P5.1                ; TURN ON MOTOR
        SJMP    MAIN_LOOP        


KQ:     CJNE    A,#'q',KW               ; IF KEY='q'
        CLR     P5.0                    ; GO FORWARD
        SJMP    MAIN_LOOP        

KW:     CJNE    A,#'w',MAIN_LOOP        ; IF KEY='w'
        SETB    P5.0                    ; GO BACKWARD
        SJMP    MAIN_LOOP

PCA_INIT:
        MOV     CMOD,#006H          ; PCA FREQUENCY = 1/Timer 0 overflow
        MOV     CCAPM2,#42H         ; PUT PCA MODULE 2 INTO PWM MODE
        MOV     CCAP2H, PWMCNT      ; INITIALIZE DUTY CYCLE
        SETB    CR                  ; START THE PCA CLOCK
        RET

CIN:
        JNB     RI,$             ; WAIT FOR A BYTE
        CLR     RI               ; CLEAR THE RECEIVE FLAG ONCE RECIEVED
        MOV     A,SBUF           ; GET THE RECEIVED BYTE INTO THE A REGISTER
        RET


        END
    
