$mod831
	keyport equ P0                 ;
	col1 equ P0.0                   
	col2 equ P0.1                   
	col3 equ P0.2                   
	col4 equ P0.3                   

	keyval equ 30H                  ;To store key number
	pressed bit 0H  	        ;Flag
	      

key_init:
        mov keyport,#0FH        
        ret

get_key:
        mov keyval,#0           ;reset the number
        mov keyport,#7FH        ;make Row1 low
        acall read_col          ;read columns

        jb pressed, done        ;check if flag is set

        mov keyval,#4           ;if not then read next row
        mov keyport,#0BFH       ;make Row2 low
        acall read_col          ;read columns

        jb pressed, done        ;check if flag is set

        mov keyval,#8           ;if not then read next row
        mov keyport,#0DFH       ;make row3 low
        acall read_col          ;read columns

        jb pressed, done        ;check if flag is set

        mov keyval,#12          ;if not read row4
        mov keyport,#0EFH       ;make row4 low
        acall read_col          ;read columns

done:
        ret

read_col:                       ;read columns routine
        clr pressed             ;reset the flag
        jb col1, nextcol        ;check if first key is pressed
        jnb col1,$              ;if yes then wait for key release  
        setb pressed            ;set the flag
        ret

nextcol:                       
        jb col2, nextcol1       ;check if second key is pressed
        jnb col2,$              ;if yes then wait for key release
        inc keyval              ;its key number 2
        setb pressed            ;set the flag
        ret

nextcol1:                    
        jb col3, nextcol2       ;check if third key is pressed
        jnb col3,$              ;if yes then wait for key release
        inc keyval              ;its key 3
        inc keyval
        setb pressed            ;set the flag
        ret

nextcol2:                     
        jb col4, exit           ;check if fourth key pressed
        jnb col4,$              ;if yes then wait for key release
        inc keyval              ;its key 4
        inc keyval
        inc keyval
        setb pressed            ;set the flag
        ret

exit:                           ;if no key is pressed
        clr pressed             ;clr the flag
        clr keyval              ;reset the number
        ret
        
end
