10.2 SPI Configuration Example

The following code examples show how to initialize the ATmega328PB SPI as master or slave. The DDR_SPI needs to be replaced by the actual port direction registers, and the DD_SS, DD_MOSI, DD_MISO, and DD_SCK to be replaced by the actual port direction register bits. For example, if the MOSI0/PB3 pin is used as MOSI, replace the DDR_SPI with the DDRB, and the DD_MOSI with the DDB3.

SPI Master configuration code example:

void SPI_MasterInit(void)

{

/* Set SS, MOSI and SCK output, all others input */

DDR_SPI = (1<<DD_SS) |(1<<DD_MOSI)|(1<<DD_SCK);

/* Enable SPI, Master, set clock rate fck/16 */

SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);

}

SPI Slave configuration code example:

void SPI_SlaveInit(void)

{

/* Set MISO output, all others input */

DDR_SPI = (1<<DD_MISO);

/* Enable SPI */

SPCR = (1<<SPE);

}