*
* Kpad4x4.asm - keypad routine for the FOX11 board
*               with BUFFALO monitor, (c)2003, EVBplus.com
*		Written by Wayne Chu
*
*     Function: It scans a keypad and outputs the key number in binary
*		format on the PB0-PB4 LEDs
*
*     Instructions:
*     If you have a 4 x 4 keypad, connect it to the keypad header J6.
*
*	   If you press any key on the keypad, the LEDs should show
*	   the key number that you pressed in binary format. Key number 00
*	   is shown as $10.

; The following signal definitions only apply to Wytec 4X4 membrane keypad:

; PD2 connects COL0 of the keypad via pin 1 of the 8-pin keypad header J6
; PD3 connects COL1 of the keypad via pin 2 of the 8-pin keypad header J6
; PD4 connects COL2 of the keypad via pin 3 of the 8-pin keypad header J6
; PD5 connects COL3 of the keypad via pin 4 of the 8-pin keypad header J6

; PE0 connects ROW0 of the keypad via pin 5 of the 8-pin keypad header J6
; PE1 connects ROW1 of the keypad via pin 6 of the 8-pin keypad header J6
; PE2 connects ROW2 of the keypad via pin 7 of the 8-pin keypad header J6
; PE3 connects ROW3 of the keypad via pin 8 of the 8-pin keypad header J6

; The PE0-PE3 has a 100K pull-up resistor in each line.

porta:		equ	0
portb:		equ	$1404
portc:		equ	$1403
portd:		equ	8
ddrd:		equ	9
porte:		equ	$0a
REGBLK:		equ	$1000


		org	$40
ram:		rmb	1
temp:           rmb     1

key_flag:	rmb	1

STACK:		equ	$FF

TEN_MS:		equ	2500	; 2500 x 8 cycles = 20,000 cycles = 10ms

	org	$D000
	jmp	start

* keypad scan for Wytec 4X4 membrane keypad
* at exit:  if a key is down, the carry bit =1 and the accumulator b
*	    holds the key number
*	    if no key is dwon the carry bit =0
*
keybrd:	ldx	#REGBLK                                                 n
	ldab	#3
*	ldaa	#11011111b
	ldaa	#$df            ; starting with pd5 is low
	staa	temp
next_row:
	staa	portd,x
	nop			; add delay before checking key down
	nop
	nop
	nop
	ldaa	porte,x
	anda	#$0f            ; needs PE0-PE3 only
	cmpa	#$0f
	bne	keyin		; key input detected
	decb
	cmpb	#$ff		; after 4 tests, accu B will be $ff
	beq	no_keyin
 	ror	temp             ; check next column
	ldaa	temp
	jmp	next_row
*
no_keyin:
	clc
	rts			; no key input

keyin: 	rora
	bcc	key_ok
	addb    #4
	jmp     keyin
key_ok: sec
	rts
*
delay_10ms:
	pshy
	ldy     #TEN_MS		; 2500 x 8 = 20,000 cycles = 10ms 
del1:	dey			; 4 cycles
	nop			; 1 cycle
	bne	del1		; 3 cycles
	puly
       	rts

*
start:	lds	#STACK
	ldx	#REGBLK
*	ldaa	#11111111b
	ldaa	#$ff
	staa	portd,x
*	ldaa 	#11111110b		; 0 =input, 1 = output
	ldaa 	#$fe			; PD0=input
	staa 	ddrd,x
*
begin:
        jsr	keybrd
	bcc	nokey
   	jsr	delay_10ms
	bcc	nokey
* key down
        tstb
	bne     not_zero
	ldab    #$10
not_zero:
	stab	portb
	jmp	begin
*
nokey:  jsr	delay_10ms
        jmp	begin
*
 	end

