; ************************************
; * Control a MAX548A with AT90S8515
; * by PEK '2002 
; *
; * The cpu take use of the internal
; * SPI routines and control the D/A.
; * Change the output voltage with
; * the five last pins on Port D. Then
; * let a interrupt occure at pin 2
; * on Port D to send the new values
; * to the D/A.
; *
; * PortB	D/A
; * ----------------
; * SS		CS
; * MOSI	DIN
; * SCK		SCLK
; ************************************


.include "8515def.inc"


; ************************************
; * Register Definitions             
; ************************************
.def	temp	=R16
.def	data	=R17
.def	volt	=R18


; ************************************
; * Start of Code                    
; ************************************
.cseg
.org 0
	rjmp	start
	rjmp	control_da


start:	ldi	temp,low(RAMEND)
	out	SPL,temp		; Set stack pointer to last internal RAM location
	ldi	temp,high(RAMEND)
	out	SPH,temp

	ldi	temp,0x00
	out	DDRD,temp		; Port D as input and
	ldi	temp,0xFF		; enable Pull-Up
	out	PORTD,temp

	ldi	temp,0x40		; Enable INT0
	out	GIMSK,temp

	ldi	temp,0b10110000		; SCK, MOSI, SS as output
	out	DDRB,temp
	sbi	PORTB,4			; SS (D/A Chip select) high from start

	ldi	temp,0b01010000		; SPE, MSTR, MAX clock rate
	out	SPCR,temp

	sei				; Enable global interrupts

loop:
	sbis	PIND,7
	ldi	volt,0xFF		; OutA=Vdd*255/256 (5V)
	
	sbis	PIND,6
	ldi	volt,0xCC		; OutA=Vdd*191/256 (4V)

	sbis	PIND,5
	ldi	volt,0x99		; OutA=Vdd*255/256 (3V)
	
	sbis	PIND,4
	ldi	volt,0x66		; OutA=Vdd*191/256 (2V)

	sbis	PIND,3
	ldi	volt,0x33		; OutA=Vdd*191/256 (1V)
		
	rjmp	loop


; Set the output of the D/A
control_da:
	cbi	PORTB,4			; Select Chip, later the MAX548 execute it's instruction with a high flank.

	ldi	data,0b00001001		; The first byte: Load and update the
	rcall	spi_send		; DAC A register of the D/A.

	mov	data,volt		; The second byte: The byte to load and
	rcall	spi_send		; update

	sbi	PORTB,4			; Now the D/A execute it's instruction
	reti

spi_send:
	out	SPDR,data		; Send byte
spi_send_loop:
	sbis	SPSR,SPIF		; Loop if transmit not complete
	rjmp	spi_send_loop
	ret
	