*******************************************************
* SPI Example -- EEL-4744  -- E.M. Schwartz           *
* 
* Main routine and subroutine to output to one of 
*    four ports using SPI. 
* See HW 8, Prob 7
*******************************************************

EEPROM	EQU	$B600
RAM	EQU	$0000
RAMEND	EQU	$01FF
BASE	EQU	$1000
DDRD	EQU	$09
SPCR	EQU	$28
SPSR	EQU	$29
SPDR	EQU	$2A
BIT7	EQU	%10000000
BIT0	EQU	%00000001

* PORTB, for example, is used for below PORT 
PORT	EQU	$04

* For below, bits 7-3 don't matter, bits 2&1 select the SPI
* port, and bit 0 is high to turn off the latches
PRT_SPI0	EQU	%00000001 
PRT_SPI1	EQU	%00000011
PRT_SPI2	EQU	%00000101
PRT_SPI3	EQU	%00000111

*   MAIN
	ORG	EEPROM
	LDS	#RAMEND
       	LDX	#BASE
	BCLR	SPCR,X BIT7	;Disable SPI interrupt
	LDAA	#%00111000	;X:X:SS:SCK:MOSI:MISO:SPR1:SPR0
	STAA	DDRD,X		;0:0: 1:  1:   1:   0:0:0
* SS (bit 5) could be 0 (input) if this pin is tied to +5V
* Speed is set for the fastest possible, 1MHz 

* Example to output to port 1 and port 2
	LDAA	#PRT_SPI1	;put PRT # info in A
	LDAB	#$37		;put data want to send out in B
	JSR	OUTPUT
	LDAA	#PRT_SPI2	;put PRT # info in A
	LDAB	#$42		;put data want to send out in B
	JSR	OUTPUT

HERE	BRA	HERE

* **********************************************************
*   Subroutine: OUTPUT
*      Inputs:  Codes for SPI port in A (PRT_SPIx)
*               Data to be output in B
*      Outputs: Data in B to SPI
*      Affected Registers:  None
* **********************************************************
OUTPUT	PSHX
	PSHA
	LDX	#BASE

	STAA	PORT,X		;Turn off shift registers and set decoder inputs
*				;  for next byte %XXXX XPT1, where PT is port # (0-3)

	LDAA	#%01011100	;SPIE:SPE:DWOM:MSTR:CPOL:CPHA:SPR1:SPR0
	STAA	SPCR,X		;   0:   1:  0:   1:   1:   1:   0:   0

	STAB	SPDR,X		;starts the process of sending out the data

* Can use the flag to detect transmission complete [shown here]
* (Need 16 E-clocks=8 microseconds for data to go out.)
****
WAIT	BRCLR	SPSR,X BIT7 WAIT	;Be sure the serial transfer is complete
	LDAA	SPDR,X			;Clear SPIF by reading SPDR (don't use data read)

* Make a low pulse on strobe to dump serial input data to the output pins (i.e., 
* trigger the latch clock) of the appropriate shift register.  Strobe is normally 
* high; make it low then high.
	BCLR	PORT,X BIT0		;strobe low
	BSET	PORT,X BIT0		;strobe high

	PULA
	PULX
	RTS
