 TITLE  "exp1"     
 List P=12F510, R=DEC
 INCLUDE "p12F510.inc"

 CBLOCK 0x10				
 freq							; ADC conversion result
 del1, del2						; used for delays
 debounce:2						; used for button debouncing
 ENDC

 PAGE
 __CONFIG _CP_OFF & _MCLRE_OFF & _WDT_OFF & _IntRC_OSC & _IOSCFS_OFF

TXEN	EQU 4
TXMOD	EQU 5                                
BUTTON	EQU	3

  org    0
	clrf	GPIO				; initialize I/O port
	movlw	b'001100'
  	tris	6       			; Enable GP3 for input
  	movlw  	b'0000000'			; Enable Internal Pull-Ups
  	option
	bcf		CM1CON0, C1ON		; comparator OFF
	movlw	b'01111001'			; ADC configuration
	movwf	ADCON0
	

loop
	call 	wait4Release		; wait 32msec for button release
	call	wait4Press			; wait 32msec for button press

	bsf 	GPIO, TXEN			; turn TX on
	bsf		ADCON0, GO			; start ADC conversion
	btfsc	ADCON0, GO			; wait for the end of conversion
	 goto	$-1	
	movf	ADRES, w
	movwf	freq

	movlw	4					; add initial 500mksec period
	addwf	freq, f

	btfss	STATUS, C			; set freq = max(freq, 255)
	 goto	freqGen
	movlw	255
	movwf	freq

freqGen
	bsf		GPIO, TXMOD			; generate frequency
	call	delay
	nop							; compensate for goto delay
	nop
	nop
	bcf		GPIO, TXMOD
	call	delay
	btfss	GPIO, BUTTON
	 goto	freqGen

	bcf 	GPIO, TXEN			; turn TX OFF
	goto 	loop

delay							; a delay for freq*100 usec
	movf	freq, w
	movwf	del1
	
dl	movlw	23					; a 100usec delay
	movwf	del2
	decf	del2, f
	btfss	STATUS, Z
	 goto	$-2	
	goto	$+1
	nop

	decf	del1, f
	btfss	STATUS, Z
	 goto	dl
	nop
	retlw	0

wait4Release
	clrf 	debounce			; wait for the button release
	clrf	debounce+1

	btfss	GPIO, BUTTON		; button released?
	 goto 	wait4Release		; NO - wait for release
	incf	debounce, f
	btfsc	STATUS, Z
	 incf	debounce+1, f
	btfss	debounce+1, 4		; 4096*8 = 32msec
	 goto	$-6
	retlw	0

wait4Press
	clrf 	debounce			; wait for the button press
	clrf	debounce+1

	btfsc	GPIO, BUTTON		; button pressed?
	 goto 	wait4Press			; NO - wait for press
	incf	debounce, f
	btfsc	STATUS, Z
	 incf	debounce+1, f
	btfss	debounce+1, 4		; 4096*8 = 32msec
	 goto	$-6
	retlw	0

	end
