SPIClass to use SPI in master mode. But if
you are developing a device that will run as a SPI slave, you need to find another way.
The sample code here shows a solution.
Three registers are used for the SPI interface.
SPCR – SPI Control RegisterSPIE: SPI Interrupt EnableSPE: SPI EnableDORD: Data OrderMSTR: Master/Slave SelectCPOL: Clock PolarityCPHA: Clock PhaseSPCR = 1 << SPE | 1 << MSTR
This enables the SPI in master mode.
SPSR – SPI Status RegisterSPIF: SPI Interrupt FlagWCOL: Write Collision FlagSPI2X: Double SPI Speed BitSPIF indicates a transfer of one byte has been completed. If so, a program
can receive and send another byte. This is how it could be checked:
if ( SPSR & 1 << SPIF )
{
// Read and write a byte
}
SPSR – SPI Data RegisterSPDR = x;
This reads a value from SPI into x:
x = SPDR;
Note that different shift registers are used for reading and writing so that the seemingly incorrect:
SPDR = x;
x = SPDR;
actually changes the value of x.
When a program writes to SPSR, the value is transmitted over SPI.
When a program reads from SPSR, a value that is received is returned.