; POT
; This program shows a technique for reading resistance. The pot input pin can
; only be changed during assembly, not once the program is running.

	device	pic16c55,xt_osc,wdt_off,protect_off
	reset	start

	org	8
temp	ds	1	; Temporary counter for delay.
potL	ds	1	; Low byte of Pot measurement.
potH	ds	1	; High byte of Pot measurement.
pot	=	ra.0	; Pin assigned to pot.
out_pot =	0	; Value to set ra.0 to output for pot.
in_pot	=	1	; Value to set ra.0 to input for pot.

	org	0
start	mov	!ra,#out_pot	; RA.0 to output.
	mov	!rb,#0		; All outputs for LEDs.
	setb	pot		; Start charging cap.
	mov	potL,#8 	; Set up for 6-ms delay: 8 trips
:wait	djnz	temp,:wait	; through outside loop x 256
	djnz	potL,:wait	; x 3 cycles for inside loop = 6.1 ms.
	clr	potL
	clr	potH
	mov	!ra,#in_pot	; Get input from pot.
	clrb	pot		; Clear output latch for pot bit.
:loop	jnb	pot,:done	; IF pot = 0 THEN :done
	mov	!ra,#out_pot	; Discharge cap a little.
	mov	!ra,#in_pot	; Change pot pin to input.
	inc	potL		; Incerement potL.
	snz			; If zero then potL overfolowed, so
	incsz	potH		; increment potH. If it overflows, exit.
	jmp	:loop		; Overflowed? No: loop.
:done	mov	temp,#2 	; Divide 16-bit number represented by
:div	clc			; potH and potL by 2^temp (in this case,
	rr	potH		; 2^2 or 4). This scales the pot value to
	rr	potL		; fit within an 8-bit range.
	djnz	temp,:div
	mov	rb,potL 	; Show the outcome on LEDs.
	jmp	start		; Do it again