;-----------
; Genesis to decoded outputs
; Written by Kevin Ahrendt
; Disclaimer: Kevin Ahrendt is not responsible for
; any damage this firmware program may cause.
;----------Assembler Directives-----------------------------------------
	list P=16F628A, F=INHX8M, C=80, N=80, ST=OFF, MM=ON, R=DEC
	include "p16f628a.inc"
        __config (_CP_OFF & _PWRTE_ON & _LVP_OFF & _BODEN_OFF & _INTRC_OSC_NOCLKOUT & _WDT_OFF & _MCLRE_ON )

;----------Equates------------------------------------------------------
Bank0Ram	equ	h'0c'
PortAMask	equ	b'11111110'	
PortBMask	equ	b'00000000'	

Select		equ	0
Data1		equ	1			; Left
Data2		equ	2			; Right
Data3		equ 3			; B/A
Data4		equ 4			; C/Start
Data5		equ	6			; Up
Data6		equ	7			; Down

CtrlLe		equ	0
CtrlRi		equ	1
CtrlUp		equ	2
CtrlDo		equ	3
CtrlA		equ	4
CtrlB		equ	5
CtrlC		equ	6
CtrlSt		equ	7

;----------Mainline program---------------------------------------------
	org h'000'
	movlw	0x07
	movwf	CMCON	
	goto Start
	nop

Start	
	movlw	PortAMask	; Set PortA/B to their inital TRIS masks and port output values
	banksel TRISA
	movwf	TRISA         
	movlw	PortBMask
	movwf	TRISB
	banksel PORTA
	clrf	PORTA

; Here starts the main work loop

	movlw	b'11111111'
	movwf	PORTB		; Sets all outputs high (Final output is active low)

Main

; Testing the controllers when select is high
	bsf PORTA,Select	; Set select high

; Check for Left
	btfss	PORTA,Data1	; If Data1 is 0, then left is pressed
	goto	LeOn
	bsf		PORTB,CtrlLe	
	goto	LeDone
LeOn
	bcf		PORTB,CtrlLe
LeDone

; Check for Right
	btfss	PORTA,Data2	; If Data2 is 0, then right is pressed
	goto	RiOn 
	bsf 	PORTB,CtrlRi
	goto	RiDone
RiOn	
	bcf		PORTB,CtrlRi
RiDone

; Check for B
	btfss	PORTA,Data3	; If Data3 is 0, then B is pressed
	goto	BOn
	bsf PORTB,CtrlB
	goto	BDone
BOn
	bcf PORTB,CtrlB
BDone


; Check for C
	btfss	PORTA,Data4	; If Data4 is low, then C is pressed
	goto	COn
	bsf 	PORTB,CtrlC
	goto	CDone
COn
	bcf PORTB,CtrlC
CDone

; Check for Up
	btfss	PORTA,Data5
	goto	UpOn
	bsf	PORTB,CtrlUp
	goto	UpDone
UpOn
	bcf	PORTB,CtrlUp
UpDone

; Check for down
	btfss	PORTA,Data6
	goto	DoOn
	bsf	PORTB,CtrlDo
	goto	DoDone
DoOn
	bcf	PORTB,CtrlDo
DoDone

; Now we test the controller for buttons when select is low
	bcf 	PORTA,Select

; Check for A
	btfss	PORTA,Data3	; If Data3 is 0, then A is on
	goto	AOn
	bsf PORTB,CtrlA
	goto	ADone
AOn
	bcf PORTB,CtrlA
ADone

; Check for Start
	btfss	PORTA,Data4
	goto StOn
	bsf PORTB,CtrlSt
	goto StDone
StOn
	bcf PORTB,CtrlSt	
StDone

; Check for Up
	btfss	PORTA,Data5
	goto	UpOn2
	bsf	PORTB,CtrlUp
	goto	UpDone2
UpOn2
	bcf	PORTB,CtrlUp
UpDone2

; Check for down
	btfss	PORTA,Data6
	goto	DoOn2
	bsf	PORTB,CtrlDo
	goto	DoDone2
DoOn2
	bcf	PORTB,CtrlDo
DoDone2

	goto Main		; Loop through this all again
;-------------------------------
	END
