$NOMOD51
$include (C8051F98x.inc)     
            
	CSEG 	AT 0				; interrupt vectors
	ljmp 	Main  			; reset

	ORG	0xB3
	USING    0                    ; specify register bank 

main:       
	anl   PCA0MD, #NOT(0x40)      ; disable the WDT
	mov	SP, #0x79			; setup stack

	acall	Ports_Setup
	acall	Clock_Setup
	acall	CS0_Setup

	acall	getCDC			;***************	
	sjmp	$-2				;***************


;-------------------PROCEDURES-------------------------------------------
Ports_Setup:
	mov  	P0MDIN,    #0xF1		; analog input on P0[3:1] 	
	mov  	P0MDOUT,   #0xF1		; push-pull out on P0[0] and P0[7:4]
	mov  	P1MDIN,    #0xFF		; digital I/O on P1
    	mov  	P1MDOUT,   #0xBF		; digital input out on P1.6
    	mov  	P0SKIP,    #0xFF		; CS input on P0.3
    	mov  	P1SKIP,    #0xFF		; I/O function on P1
    	mov   XBR2,      #0x40		; enable XBar and weak pull-ups	
	mov	P0, 	     #0x1E
	mov	P1, 	     #0x40		; initialize port pins
	ret

;-----------------------------------------------------------------------
Clock_Setup:
	mov	SFRPAGE, #0xF		; switch to SFR page 0xF
	mov	PMU0MD, #0			; enable POR supply monitor
	mov	SFRPAGE, #0			; switch to default SFT page
	mov 	RSTSRC, #0x06		; enable MCD and VDD monitor
	anl	OSCICN, #NOT(0x80)	; disable internal precision oscillator
	mov	REG0CN,  #0			; disable precision oscillator bias
	mov	OSCXCN, #0			; disable external oscillator
	mov	CLKSEL, #0x04		; select LFO with 1:1 clock divider
	orl	FLSCL, #BYPASS		; set the one-shot bypass bit
	mov	A, CLKSEL			; wait for the divider setting to be applied
	anl	A, #0x80		
	jz	$-4		
	ret

;-----------------------------------------------------------------------
CS0_Setup:
	mov	CS0CN,   #0x80		; enable Capacitive Sense module CS0
	mov	CS0CF,   #0x00		; accumulate 1 sample
	mov	CS0MD1,  #0x00		; gain = 1x
	mov	CS0MD2,  #0x28		; set 12-bit resolution, 3 usec discharge 

;	mov	SFRPAGE, #0xF		; swtich to SFR page 0xF	
;	mov	CS0MD3,  #0x18		; set ramp time
;	mov	SFRPAGE, #0			; switch to default SFR page	

	mov	CS0MX,   #0x02		; select channel P0.3
	mov	CS0CN,   #0x00		; turn the module off
	ret


;-----------------------------------------------------------------------
getCDC:
	mov	CS0CN,   #0x80		; enable Capacitive Sense module CS0
	nop
	orl	CS0CN, #0x10		; start conversion
	nop
	nop
	mov	A, CS0CN			; poll BUSY flag
	anl	A, #0x10
	jnz	$-5               	

	mov	CS0CN, #0x00		; power-off CS0 module
	ret

END