2 Setup the SPI

The configuration of the SPI in master mode will be shown in two different ways. The first example will show how to implement an SPI communication which is controlled by polling the interrupt flags. The second example will show how to implement an interrupt controlled communication.

A communication between two AVR devices is shown by sending a text string from the part configured as master to the other part configured as slave. The received character is compared with the expected one (transmitted character) and the result of this communication test is output on the Port D in slave. These examples are well suited to be implement by using two development boards like the STK®600.

In all the examples shown here the SPI is configured to run in mode 0 with MSB transmitted first. This is done by setting the bits CPOL, CPHA and DORD in the register SPCR to zero. In the same register the SPI is enabled by setting the SPE bit, while the SCK frequency is specified to CK/4 in the first example . It is set to CK/16 in the second example.

To compare the configuration of the SPI in the different examples the attention has to be directed on the settings of the Master / Slave Select (MSTR) bit and the SPI Interrupt Enable (SPIE) bit.
Note:
  1. Because both examples show the transmission between a single master and a single slave it is not necessary to check if the MSTR bit is still set before the master initiates a new transmission. This code has to be added in a multi master application.
  2. Although the settings of the Clock Rate Select bits have no effect in slave mode it has to be ensured that the system clock (CK) of the slave is at least four times higher than the SPI clock (SCK).
  3. Pending SPI interrupts are cleared by a dummy access to the SPSR and the SPDR.

Both the master and the slave projects developed in Atmel Studio 7 are available along with this application note.

To run the code, setup two STK600 development boards as shown in the following figure.The MISO, MOSI and SCK lines of both master and slave are connected together. The SS of slave should be connected to the ground. Ensure that both the STK600 boards are connected to common ground. The code is written for ATmega162, but can be compiled for any part with hardware SPI and PORTA, PORTB and PORTD. In this application, when any one of the switches connected to the master is pressed the SPI transmission is initiated.
Figure 2-1. Hardware Setup