*******************************************************
* SPI Example -- EEL-3744/4744 -- E.M. Schwartz       *
* 
* Main routine and subroutine to output to one of 
*    four ports using SPI. 
* See HW Prob
*******************************************************

STACK	EQU	$900
SP0CR1	EQU	$D0	; SPI Control Register 1
SP0CR2	EQU	$D1	; SPI Control Register 2
SP0BR	EQU	$D2	; SPI Baud Register
SP0SR	EQU	$D3	; SPI Status Register
SP0DR	EQU	$D5	; SPI Data Register
PORTS	EQU	$D6	; Serial Port Registor 
*			;   SPI: Bits 7-4 SS, SCK, MOSI, MISO
*			;   SCI: Bits 1-0 Tx, Rx
DDRS	EQU	$D7	;DATA DIRECTION REGISTER

RAM	EQU	$0900	; Start of RAM
STK	EQU	$0A00	; User Stack
RAMPROG	EQU	$0970	; Program space in RAM

* MASKS
BIT765	EQU	%11100000
BIT7642 EQU	%11010100
BIT7	EQU	%10000000
BIT4	EQU	%00010000
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	RAMPROG
	LDS	#STACK

	BCLR	SP0CR1 BIT7	;Disable SPI interrupt

* ENABLE SPI OUTPUTS
	BSET	DDRS BIT765	;outputs SS-SCK-MOSI
	BCLR	DDRS BIT4	;input MISO
* SS (bit 7) could be 0 (input) if this pin is tied to +5V

* Speed is set for the fastest possible, E/2=1MHz 
	LDAA	#0		;Speed E/2 = E / X
	STAA	SP0BR 		;  where X = 2^(SPR+1) 

* 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
* **********************************************************
	ORG	$9C0
OUTPUT	PSHX
	PSHA

	STAA	PORT		;Turn off shift registers and set decoder inputs
*				;  for next byte %XXXX XPT1, where PT is port # (0-3)

	LDAA	#%01011100	;SPIE:SPE:SWOM:MSTR:CPOL:CPHA:  ??:  ??
	STAA	SP0CR1		;   0:   1:  0:   1:   1:   1:   0:   0

	STAB	SP0DR		;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	SP0SR BIT7, WAIT	;Be sure the serial transfer is complete
	LDAA	SP0DR			;Clear SPIF by reading SP0DR (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 BIT0		;strobe low
	BSET	PORT BIT0		;strobe high

	PULA
	PULX
	RTS
