2.1 Configuration Overview
When configuring the SPI module on a PIC® device, the first step should be to ensure that all devices have been connected correctly in hardware on the SPI bus. Once the master device has been connected to all slave devices in hardware, the next step is to assign necessary pins for SPI communication in software. The SPI signals can be rerouted to different pins using the Peripheral Pin Select (PPS) feature on newer microcontrollers. Refer to the device data sheet for rerouting options. Configuration of these pins, along with the configuration of the microcontroller, should all be a part of the initial device setup.
After the pins and system have been configured, the next step is to initialize the SPI module in software. The example below shows how to initialize the system oscillator, configure the SPI pins using Peripheral Pin Select and initialize the SPI module. The main SPI module control registers are SPIxCON0, SPIxCON1, and SPIxCON2. In addition to those registers, the SPIxBAUD register and the SPIxCLK registers are initialized in this example to demonstrate setting the frequency of the SCK output signal.
BASIC SETUP AND INITIALIZATION OF THE SPI MODULE
// Oscillator Configuration
OSCCON1 = 0x60; // HFINTOSC; NDIV = 1;
OSCCON3 = 0x00; // CSWHOLD may proceed; SOSCPWR Low power;
OSCEN = 0x00; // Oscillator Manual Enable Register;
OSCFRQ = 0x03; // HFINTOSC = 8 MHz;
OSCTUNE = 0x00; // // Calibrated Frequency (Default);
// Port Configuration
TRISA = 0x00; // RA3 = output;
TRISB = 0x10; // RB1 = input, RB3 = output;
ANSELA = 0x00; // Digital I/O;
ANSELB = 0x00; // Digital I/O;
SPI1SDIPPSbits.SPI1SDIPPS = 0x0A; // RB2->SPI1:SDI1; -- input;
RB1PPS = 0x1E; // RB1->SPI1:SCK1; -- output;
RB3PPS = 0x1F; // RB3->SPI1:SDO1; -- output;
RA3PPS = 0x20; // RA3->SPI1:SS1; -- output;
// SPI Configuration
SPI1CON1 = 0x64; // CKE; CKP; SDI/SDO Polarity;
SPI1CON2 = 0x07; // TXR; RXR;
SPI1BAUD = 0x07; // SPI Baud Pre-Scaler;
SPI1CLK = 0x00; // SPI Clock Select;
SPI1CON0 = 0x83; // SPI Enable; BMODE; Master/Slave; MSb/LSb;