 TITLE  "wRX2.asm"          	; PLL controller for BH1417f
 List P=12F683, R=DEC
 INCLUDE "p12F683.inc"

; data segment
 CBLOCK 0x20                   
 freqNo, freqCode				; freq code values 7 and 15 translate to 8 and 16
 debounce:2 	 	 			; variable bor button debouncing
 ENDC

; code segment
 __CONFIG _BOD_ON & _CPD_OFF & _CP_OFF & _MCLRE_OFF & _PWRTE_ON & _WDT_OFF & _INTOSCIO

  ORG 0	                    	; start program at the beginning of mem
	bcf		STATUS, RP0         ; switch to BANK 0
	movlw	b'110000'			; initialize GPIO
	movwf	GPIO
	movlw	7
	movwf	CMCON0				; comparator off
	clrf	ADCON0				; ADC OFF
  	bsf    	STATUS, RP0      	; change to BANK 1
	clrf	VRCON ^ 0x80		; disable the voltage reference
	clrf	ANSEL ^ 0x80 		; digital function on all pins
	movlw	b'00001000'
	movwf	TRISIO ^ 0x80		; configure all GPIO pins for output
  	bcf    	STATUS, RP0        	; back to BANK 0

;	clrf 	freqNo				; for the lower part of the FM band
	movlw	7					; for the higher part of the FM band
	movwf	freqNo
	goto	setFreq

loop							; main loop
 	call 	wait4Release		; wait 128msec for button release
	call	wait4Press			; wait 128msec for button press

	incf	freqNo, f			; freq = freq+1 (mod 14)
	movlw	14
	subwf	freqNo, w
	btfss	STATUS, Z
	 goto	continue
;	 clrf	freqNo				; reset the freq in the cyclic order
	movlw	7					
	movwf	freqNo

continue
	movlw	7					; set GPIO:5=1 if freqCode >= 7
	subwf	freqNo, w           ; and 0 otherwise
	btfss	STATUS, C
	 bcf	GPIO, 5	
	btfsc	STATUS, C
	 bsf	GPIO, 5

setFreq
	call	getCode				; get freq code in freqCode
	movwf	freqCode
	
	movf	GPIO, w				; read GPIO port
	andlw	b'00101000'
	iorwf	freqCode, w
	movwf	GPIO				; update GPIO
	goto 	loop

getCode
	movf	freqNo, w			; by using 7.68MHz crystal, the frequencies
	addwf	PCL, f				; are shifted 1MHz up
	retlw	0					;  87.7 	(all data is for 7.6MHz crystal)
	retlw	1					;  87.9
	retlw	4					;  88.1
	retlw	5					;  88.3
	retlw	2					;  88.5
	retlw	3					;  88.7
	retlw	6					;  88.9
	retlw	16					; 106.7
	retlw	17					; 106.9
	retlw	20					; 107.1
	retlw	21					; 107.3
	retlw	18					; 107.5
	retlw	19					; 107.7
	retlw	22					; 107.9
	
wait4Release
	clrf 	debounce			; wait for the button release
	clrf	debounce+1

	btfss	GPIO, 3				; button released?
	 goto 	wait4Release		; NO - wait for release
	incf	debounce, f
	btfsc	STATUS, Z
	 incf	debounce+1, f
	btfss	debounce+1, 6		; 16384*8 = 128msec
	 goto	$-6
	return

wait4Press
	clrf 	debounce			; wait for the button press
	clrf	debounce+1

	btfsc	GPIO, 3				; button pressed?
	 goto 	wait4Press			; NO - wait for press
	incf	debounce, f
	btfsc	STATUS, Z
	 incf	debounce+1, f
	btfss	debounce+1, 6		; 16384*8 = 128msec
	 goto	$-6
	return

 end