Theory of Operation
The Serial Peripheral Interface Bus or SPI bus is a synchronous serial data link used to communicate between two or more microcontroller and devices supporting SPI mode data transfer. Devices communicate in master/slave mode where the master device initiates the data frame. Multiple slave devices are allowed with individual slave select (chip select) lines.
This communication protocol consists of folliwng lines or pins,
- MOSI : Master Out Slave In (Tx for Master and Rx for Slave)
- MISO : Master In Slave Out (Rx for Master Tx for Slave)
- SCK : Serial Clock (Clock line)
- SS : Slave Select (To select Slave chip) (if given 0 device acts as slave)
Master: This device provides the serial clock to the other device for data transfer. As a clock is used for the data transfer, this protocol is Synchronous in nature. SS for Master will be disconnected.
Slave: This device accepts the clock from master device. SS for this has to be made 0 externally.


Setting up SPI in Microcontroller

Master Microcontroller
Open Code Wizard and go to SPI tab. Enable SPI and choose Master in SPI Type.
Select clock rate depending upon your data transfer speed requirement.
Keep other settings as default.

Slave Microcontroller
Open Code Wizard and go to SPI tab. Enable SPI and choose Slave in SPI Type.
Select clock rate depending upon your data transfer speed requirement.
Keep other settings as kept in the master microcontroller.
Data Transfer Functions
You can transmit or receive 1 byte of data at a time.
Transmit Data
spi(1 byte data);
Example: spi(‘A’);
Receive Data
c = spi(0); // c is 1 byte variable
Example: char c = spi(0);