µC support various wire communication protocols i.e. UART or UASRT communication, SPI, TWI etc. SPI is the simplest of all communication system. In SPI data communication take place between two devices, commonly known as Master and slave. The device or devices that control the operation inside the network is known as Master and the device or devices that attached known as Slave. In AVR the SPI communication uses four pins-

Thus pins have many alternative names. Some are listed bellow-


Atmel microcontroller can be configured as both Master and Slave. Before we discuss let looks at the SPI registers available and there uses-



The coding for configure as Master as follow-
#define SPI_DDR DDRx
#define SPI_ MOSI DDx
#define SPI_ SCK DDx
#define SPI_SS DDx
#define SPI_ MISO DDx
#define SPI_PORT PORTx
#define SPI_CS PINx
SPI_DDR|=(1<< SPI_ MOSI)|(1<< SPI_ SCK)|(1<< SPI_SS);
SPI_DDR&=~(1<< SPI_ MISO);
SPI_PORT&=~(1<<SPI_CS); //Chip selection
SPCR|=(1<<SPE); //SPI Enable
SPCR|=(1<<MSTR); //Set as Master
SPCR|=(1<<SPR1)|(1<<SPR0); //Clock select


The coding for configuring as Slave as follow-
#define SPI_DDR DDRx
#define SPI_ MOSI DDx
#define SPI_ SCK DDx
#define SPI_SS DDx
#define SPI_ MISO DDx
#define SPI_PORT PORTx
#define SPI_CS PINx
SPI_DDR&=~((1<< SPI_ MOSI)|(1<< SPI_ SCK)|(1<< SPI_SS);
SPI_DDR|=(1<< SPI_ MISO);
SPCR|=(1<<SPE); //SPI Enable
SPCR&=~(1<<MSTR); //Set as Slave
SPCR|=(1<<SPR1)|(1<<SPR0); //Clock select
After selecting AVR Master or Slave, it is time to communicate between master and slave. For data communication SPDR register is used which is full duplex. Means that data can be both transmit and receive at the same time. So that data can be transmit by writing data to SPDR register, that-
- SPDR=data
And data can be received by receiving the SPDR register that
- data=SPDR
So it is very easy to transmit and receive data through SPDR register, but it should be configure first if SPDR register is ready to transmit/receive data. It is interesting that SPIF bit of SPSR register is set whenever the data transmit is complete even if interrupts are not enable. So we use the flag register for our safety and error free programming. So we separate SPI read and SPI write operation.
SPI Write
void SPIWrite(unsigned char datain)
{
SPDR = datain; // send the data
while(!(SPSR & (1<<SPIF)))
{
; // wait until transmission is complete
}
}
SPI Read
unsigned char SPIRead(void)
{
while(!(SPSR & (1<<SPIF)))
{
; // wait until all data is received
}
return SPDR;
}
For your better understand we give a program in which ATmega32 as Master and ATmega8 as Slave. We will discuss more about SPI and communication between AVR with other peripherals in the next article. Download the program and understand the logic-







Visit Today : 47
Total Visit : 28462