
	LIST P=18F442
	#include <P18F442.INC>	; File contains addresses for register and bit names

;************************************************************
; variables

TEMP	equ	0x001	
UST	equ	0x002
ALT	equ	0x003
VREF	equ	0x004
DELTA	equ	0x005

;************************************************************
; reset and interrupt vectors

	org	0x00000	; Reset Vector Address
	goto	Start

	org	0x00008	; Interrupt Vector Address
	goto	ISR	; goto Interrupt Service Routine	

;************************************************************
; program code starts here

	org	0x00020
Start
	clrf	PORTD		; clear all bits of PORTD	
	clrf	TRISD		; Set PORTD as outputs

	call	InitializeAD 	; configure A/D module
	
	call	SetupDelay	; delay for 15 instruction cycles
	
	call	InitializeONOFF

	bsf	ADCON0,GO	; Start first A/D conversion

Main	goto	Main		; do nothing loop

;************************************************************
; Service A/D interrupt
; Get value and display on LEDs

ISR
	; Save context (WREG and STATUS) if required.

	btfss	PIR1,ADIF	; Did A/D cause interrupt?
	goto	OtherInt	; No, check other sources
	
	movf	ADRESH,W	; Get A/D value
	cpfsgt	UST
	bsf		LATD,0
	cpfslt	ALT
	bcf		LATD,0

	bcf		PIR1,ADIF	; Reset A/D int flag

	call	SetupDelay	; Delay for 15 cycles

	bsf		ADCON0,GO	; Start A/D conversion

	goto	EndISR		; return from ISR

OtherInt
	; This would be replaced by code to check and service other interrupt sources
	goto	$	; trap here, loops to self

EndISR
	; Restore context if saved.

	retfie		; Return, enables GIE

InitializeAD
	movlw	B'00000100'	; Make RA0,RA1,RA4 analog inputs
	movwf	ADCON1

	movlw	B'11000001'	; Select RC osc, AN0 selected,
	movwf	ADCON0		; A/D enabled

	bcf	PIR1,ADIF	; Clear A/D interrupt flag
	bsf	PIE1,ADIE	; Enable A/D interrupt
	
	bsf	INTCON,PEIE	; Enable peripheral interrupts
	bsf	INTCON,GIE	; Enable Global interrupts

	return

InitializeONOFF
	movlw	.128
	movwf	VREF
	movlw	.40
	movwf	DELTA

	movf	VREF,W
	addwf	DELTA,W
	movwf	UST
	movf	DELTA,W
	subwf	VREF,W
	movwf	ALT

	return

SetupDelay
	movlw	.3		; Load Temp with decimal 3
	movwf	TEMP
SD
	decfsz	TEMP, F		; Delay loop
	goto	SD
	return

	END

