
SCAN_MATRIX_KEYBOARD:
     acall   DELAY ; calls the 30 MS delay subroutine
     mov     a, p1 ; mov the value of p1 to acc
     push    acc   ; value of acc is preserved
     anl     a, #0fh ; higher nibble is made low ie ROW
     cjne    a, #0fh, AHEAD ;if the Lower Nibble ie Coulmn reading is not high then 
                            ; it means any column has been pressed
                            ; jump to subroutine AHEAD
     sjmp    SCAN_MATRIX_KEYBOARD ; otherwise LOOP

AHEAD:
     pop     acc ; get back the original value of p1 
     anl     a, #0f0h ; Make lower Nibbles ie column low
     cjne    a, #0f0h, PROCESS_SCAN ; if the higher nibbles ie ROW are not high
                                    ; it means any ROW is pressed
                                    ; then jump to PROCESS_SCAN
     sjmp    SCAN_MATRIX_KEYBOARD ; otherwise LOOP

PROCESS_SCAN:
      mov    a, p1 ; once agin move the value of p1 to acc
      cpl    a ; compliment it and find whether actually a key is pressed or not
      jz     SCAN_MATRIX_KEYBOARD ; 
      cpl    a ; get the original value of p1
      push   acc ; preserve this value of p1
      anl    a, #0fh 
      cjne   a, #0fh, ROW_SCAN_1 ;; again check any column had been pressed or not

      sjmp   SCAN_MATRIX_KEYBOARD

ROW_SCAN_1:
      pop   acc ; get the original value of acc agian to check which row is pressed
      anl   a, #0f0h ; make higher nibbles high 
      cjne  a, #0e0h, ROW_SCAN_2 ; if ROW 1 has been pressed then jump to ROW_1 
                                 ; otherwise jump to ROW_2 checking
      sjmp  ROW_1

ROW_SCAN_2:
     cjne   a, #0d0h, ROW_SCAN_3
     sjmp   ROW_2

ROW_SCAN_3:
     cjne   a, #0b0h, ROW_SCAN_4
     sjmp   ROW_3

ROW_SCAN_4:
     cjne   a, #70h, SCAN_MATRIX_KEYBOARD
     sjmp   ROW_4

ROW_1:
     mov    dptr, #CODE1
     sjmp   FINAL

ROW_2:
     mov    dptr, #CODE2
     sjmp   FINAL

ROW_3:
     mov    dptr, #CODE3
     sjmp   FINAL

ROW_4:
     mov    dptr, #CODE4

FINAL:
     mov     a, p1 ; get the original value of p1 so that the COlumn can be sestimated from here
     clr     c ; clear carry flag

SUB_FINAL:
     rrc     a ; rotate right untill carry is clear
     jnc     MATCH ; if the carry is clear then jump to MATCH
     inc     dptr ; if carry is not clear then increment the DPTR
     sjmp    SUB_FINAL ; LOOP

MATCH:
     clr     a ; clear acc
     movc    a,@a+dptr ; move the value of dptr to ACC
     ;mov    r6, a
     push    acc ; preserve this value
     ret


CODE1: db '1','2','3','4'
CODE2: db '5','6','7','8'
CODE3: db '9','10','11','12'
CODE4: db '13','14','15','16'

