The following code examples show how to initialize the SPI as a master and how to perform a simple transmission.
DDR_SPI in the examples must be replaced by the actual data direction register controlling the SPI pins. DD_MOSI,
DD_MISO and DD_SCK must be replaced by the actual data direction bits for these pins. E.g. if MOSI is placed on pin PB2,
replace DD_MOSI with DDB2 and DDR_SPI with DDRB.
Assembly Code Example(1)
SPI_MasterInit:
; Set MOSI and SCK output, all others input
ldi
out
r17,(1<<DD_MOSI)|(1<<DD_SCK)
DDR_SPI,r17
; Enable SPI, Master, set clock rate fck/16
ldi
out
ret
r17,(1<<SPE)|(1<<MSTR)|(1<<SPR0)
SPCR,r17
SPI_MasterTransmit:
; Start transmission of data (r16)
out
SPDR,r16
Wait_Transmit:
; Wait for transmission complete
sbis
rjmp
ret
SPSR,SPIF
Wait_Transmit
C Code Example(1)
void SPI_MasterInit(void)
{
/* Set MOSI and SCK output, all others input */
DDR_SPI = (1<<DD_MOSI)|(1<<DD_SCK);
/* Enable SPI, Master, set clock rate fck/16 */
SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0);
}
void SPI_MasterTransmit(char cData)
{
/* Start transmission */
SPDR = cData;
/* Wait for transmission complete */
while(!(SPSR & (1<<SPIF)))
;
}
Note:
1. The example code assumes that the part specific header file is included.
ATmega16/32/64/M1/C1 [DATASHEET]
135
7647O–AVR–01/15