Simple program for master to send data to slave over SPI
Master Program
/*
* Program for Master SPI
*/
#include <hc11.h>
main()
{
unsigned char master_dataout;
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;
PORTD &= ~0x20; /* Bring Bit 5 of Port D low to select
slave HC11 */
temp = SPSR; /* Read SPSR as first step in clearing
SPIF */
master_dataout = 0xaa;
SPDR = master_dataout; /* Send data to slave; clears SPIF */
while ((SPSR & 0x80) == 0) ; /* Wait for transfer to finish */
PORTD |= 0x20; /* Bring Bit 5 of Port D high to deselect
slave HC11 */
/* Rest of program */
}
Slave Program
/*
* Program for Slave SPI
*/
#include <hc11.h>
main()
{
unsigned char slave_datain;
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 */
temp = SPDR; /* Read SPDR to finish clearing SPIF */
while ((SPSR & 0x80) == 0) ; /* Wait for transfer to finish */
slave_datain = SPDR; /* Read data from slave;
this also clears SPIF flag */
}