SPI Mode Operation

When initializing the SPI, several options need to be specified. This is done by programming the appropriate control bits (SSPxCON1[5:0] and SSPxSTAT[7:6]). These control bits allow the following to be specified:

To enable the serial port, the SSP Enable (SSPEN) bit must be set. To reset or reconfigure SPI mode, clear the SSPEN bit, re-initialize the SSPxCONy registers and then set the SSPEN bit. The SDI, SDO, SCK and SS serial port pins are selected with the PPS controls. For the pins to behave as the serial port function, some must have their data direction bits (in the TRIS register) appropriately programmed as follows:

Any serial port function that is not desired may be overridden by programming the corresponding data direction (TRIS) register to the opposite value.

The MSSP consists of a Transmit/Receive Shift Register (SSPSR) and a buffer register (SSPxBUF). The SSPSR shifts the data in and out of the device, MSb first. The SSPxBUF holds the data that was written to the SSPSR until the received data is ready. Once the eight bits of data have been received, that byte is moved to the SSPxBUF register. Then, the Buffer Full Status (BF) bit and the MSSP Interrupt Flag (SSPxIF) bit are set. This double-buffering of the received data allows the next byte to start reception before reading the data that was just received. Any write to the SSPxBUF register during transmission/reception of data will be ignored and the Write Collision Detect (WCOL) bit will be set. User software must clear the WCOL bit to allow the following write(s) to the SSPxBUF register to complete successfully.
When the application software is expecting to receive valid data, the SSPxBUF must be read before the next byte of data to be transferred is written to the SSPxBUF. The BF bit indicates when SSPxBUF has been loaded with the received data (transmission is complete). When the SSPxBUF is read, the BF bit is cleared. This data may be irrelevant if the SPI is only a transmitter. The MSSP interrupt is used to determine when the transmission/reception has completed. If the interrupt method is not going to be used, then software polling can be done to ensure that a write collision does not occur.
Important: The SSPSR is not directly readable or writable and can only be accessed by addressing the SSPxBUF register.