
$include (c8051f500.inc)     ;Use C8051F50x predefined symbols

;-------------------------------------------
;Assign names to port pins
PULSE EQU P1.7 
SCK EQU P2.0
MISO EQU P2.1
MOSI EQU P2.2
CS EQU P2.3
;---------------------------------------------------------------------------
CSEG                 ;Define the following as code
ORG 0000h            ;Load code starting at 0000h
JMP MAIN             ;Jump to MAIN
;---------------------------------------------------------------------------
ORG 000bh            ;Timer 0 interrupt subroutine

CLR TR0              ;Stop Timer 0
CLR TF0              ;Clear Timer 0 overflow flag
DEC R2               ;Decrement R0
SETB 00h             ;Set bit located at 00h
RETI                 ;Return from interrupt
;----------------------------------------------------------------------------

ORG 060h             ;Start MAIN outside ISR Space

MAIN: 

MOV SPI0CN, #01h     ;Config SPI
MOV P1MDOUT,#80h     ;Set P1.7 to push-pull
MOV P2MDOUT,#008h    ;Set P2.3 to push-pull
MOV P0SKIP,#0FFh     ;Force crossbar to skip all P0 pins
MOV P1SKIP,#0FFh     ;Force crossbar to skip all P1 pins
MOV P2SKIP,#008h     ;Force crossbar to skip P2.3
MOV XBR0,#04h        ;Enable SPI I/O routing to port pins
MOV XBR2,#40h        ;Enable the Crossbar
SETB EA              ;Enable interrupts
SETB ET0             ;Enable Timer 0 interrupt 

MOV TMOD,#01         ;Put Timer 0 in 16-bit mode
;---------------------------------------------------------------------------
REQUEST:

CLR CS               ;Write a zero to CS pin to initiate SPI comm
MOV SPI0DAT,#'h'     ;Send an 'h' to request the current heading 
JNB TXBMT,$          ;Wait here until the transmit buffer is clear
JNB SPIF,$           ;Wait here until the SPI receive flag goes high
MOV R0,SPI0DAT       ;Move the contents of the SPI receive 
                     ;buffer to R0 (high byte)
CLR SPIF             ;Clear the SPI receive flag
JNB SPIF,$           ;Wait here until another 8 bits have been received
MOV R1, SPI0DAT      ;Move the contents of the SPI receive
                     ;buffer to R1 (low byte)
SETB CS              ;Write a 1 to CS to stop the SPI communication
CLR SPIF             ;Clear the SPI receive flag
MOV R2,25            ;Move a value of 25 to the R2 register

WAIT:

CLR 00h              ;Clear 00h before restarting WAIT loop
MOV TH0,#76          ;Set T0 high byte to 19,456
MOV TL0,#00          ;Set T0 low byte to 0
SETB TR0             ;Turn on Timer 0 to wait for heading data
JNB 00h,$            ;Wait here until 00h is set
CJNE R2,#0h,WAIT     ;Jump back to wait if R0 does not equal 0
                     ;This forces the program to pause
                     ;before requesting another heading
                     ;from the compass
LJMP REQUEST         ;Jump back to request to start heading request 


END

