Simple program for slave to send data to master over SPI.
The slave uses Bit 0 of PIA Port B to signal the master it has data to
send. The master uses Bit 0 of PIA Port A to receive signal from slave.
Master Program
/*
* Program for Master SPI
*/
#include
main()
{
unsigned char master_datain;
unsigned char temp;
DDRD |= 0x38; /* Make Bit 3 (MOSI), Bit 4 (SCK),
and Bit 5 of Port D outputs */
/*
* SPCR = 0 1 0 1 0 1 0 0
* | | | | | | | |
* | | | | | | \_\____SPI Clock = E/2 (1 MHz)
* | | | | | \________CPHA = 1 (data valid on 2nd SCK edge;
* | | | | | SS can remain active low
* | | | | | between bytes.)
* | | | | \__________CPOL = 0 (SCK idle low)
* | | | \____________MSTR = 1 (master)
* | | \______________DWOM = 0 (do not use wired-OR mode)
* | \________________SPE = 1 (enable SPI)
* \__________________SPIE = 0 (do not enable interrupts)
*/
SPCR = 0x54;
while ((PIA_A & 0x01) == 0) ; /* Wait for signal from slave */
PORTD &= ~0x20; /* Bring Bit 5 of Port D low to select
slave HC11 */
temp = SPSR; /* Read SPSR as first step in clearing
SPIF */
SPDR = 0; /* Send junk to slave; clears SPIF */
while ((SPSR & 0x80) == 0) ; /* Wait for transfer to finish */
master_datain = SPDR; /* Read data from slave;
this also clears SPIF flag */
PORTD |= 0x20; /* Bring Bit 5 of Port D high to deselect
slave HC11 */
}
Slave Program
/*
* Program for Slave SPI
*/
#include
main()
{
unsigned char slave_dataout;
unsigned char temp;
DDRD |= 0x04; /* Make Bit 2 of Port D (MISO) an output */
/*
* SPCR = 0 1 0 0 0 1 0 0
* | | | | | | | |
* | | | | | | \_\____Don't care for slave
* | | | | | \________CPHA = 1 (data valid on 2nd SCK edge;
* | | | | | SS can remain active low
* | | | | | between bytes.)
* | | | | \__________CPOL = 0 (SCK idle low)
* | | | \____________MSTR = 0 (slave)
* | | \______________DWOM = 0 (do not use wired-OR mode)
* | \________________SPE = 1 (enable SPI)
* \__________________SPIE = 0 (do not enable interrupts)
*/
SPCR = 0x44;
temp = SPSR; /* First step in clearing SPIF */
slave_dataout = 0xaa;
SPDR = slave_dataout; /* Send data to slave; clears SPIF */
PIA_B = 0x01; /* Signal master to read data */
while ((SPSR & 0x80) == 0) ; /* Wait for transfer to finish */
}