; ************************************
; * ADC Access  by PEK '2000
; *
; * The program use the ADC and sample
; * in Free Run Mode. Every second
; * Port-B show the newest sampled
; * value (8 MS Bits).
; *
; * Use a 4 MHz crystal and an AT90S8535
; ************************************


.include "8535def.inc"


; ************************************
; * Register and Variable Definitions             
; ************************************
.def	temp	=R16
.def	adcdata	=R17


; ************************************
; * Start of Code                    
; ************************************
.cseg
.org 0
	rjmp	Start
.org 6	
	rjmp	Show			; Timer1 CompareA Handler


Start:	ldi	temp,low(RAMEND)
	out	SPL,temp		; Set stack pointer to last internal RAM location
	ldi	temp,high(RAMEND)
	out	SPH,temp

; ** Setup ADC ***********************
	ldi	temp,0xA7		; ADC Enable, Free Run Mode, Prescaler = 128
	out	ADCSR,temp
	sbi	ADCSR,ADSC		; Start conversion

	ldi	temp,0x00		; Measuring on ADC-pin 0
	out	ADMUX,temp

; ** Setup Ports *********************
	ldi	temp,0xFF
	out	DDRB,temp		; Port B as output

; ** Setup Timer *********************
	cli				; Disable global interrupts
	ldi	temp,0
	out	TCCR1A,temp		; Disable Compare Output Mode and PWM
	ldi	temp,0x0C
	out	TCCR1B,temp		; Enable CTC1 and CK/256
	ldi	temp,0x10	
	out	TIMSK,temp		; Enable T/C Output CompareA Match Interrupt 
	ldi	temp,61
	out	OCR1AH,temp		; 16-bit Counter compare value (1 sek at 4 MHz (CK/256))
	ldi	temp,9			; (9 + 61*256)*256
	out	OCR1AL,temp

	sei				; Enable global interrupts

; ** Main Loop ***********************
Loop:
	rjmp	Loop


; ** Timer1 CompareA ISR *************
Show:
	in	temp,ADCL		; Read the least significant ADC bits
	in	adcdata,ADCH		; Read the most significant ADC bits

	ror	adcdata			; Move the 8 most significiant bits in
	ror	adcdata			; one register, adcdata.
	ror	adcdata
	andi	adcdata,0xC0
	ror	temp
	ror	temp
	andi	temp,0x3F
	or	adcdata,temp

	out	PORTB,adcdata		; Out on PortB
	reti