How to Program SPI in PIC16F877A (Slave Mode)

The following code demonstrate, how to write a program to use SPI (serial peripheral interface) in slave mode. Timer-2 is used to provide clock to SPI module, so you can not use Timer-2 for any other purpose if you are using SPI module. One controller is running in master SPI mode, while the other is running in slave mode. Master send a up counter value to the slave controller. The slave controller receive data and write received data to PORTD. SPI has the four wire interface:
  1. SCK (PORTC.3) Serial clock output from master and input to slave [SCK]
  2. SDI (PORTC.4) Serial data input to master and output from slave [SDO]
  3. SDO (PORTC.5) Serial data output from master and input to slave [SDI]
  4. SS (PORTA.5) Slave select active low output from master and input to slave [SS]
The SPI data is monitored on SPI debuger and also all signals are displayed on oscilloscope. The code is written in “mikroC PRO for PIC v.5.6.1” IDE and simulation is done with Proteus 8.0 SP0. At the end of code, you can find complete project files for download.

Code in mikroC

// set direction
sbit LED_Dir at TRISB.B0;
sbit SS_Dir at TRISA.B5;
sbit SCLK_Dir at TRISC.B3;
sbit SDO_Dir at TRISC.B5;
sbit SDI_Dir at TRISC.B4;
sbit SS at PORTA.B5;
sbit LED at PORTB.B0;
void main(void)
{
unsigned short buffer = 0x00;
unsigned short receive_data = 0x00;
// set as output
LED_Dir = 0;
SS_Dir = 0;
SCLK_Dir = 0;
SDO_Dir = 0;
TRISD = 0x00;
PORTD = 0x00;
// set as input
SDI_Dir = 1;
// Set SPI1 module to master mode,
// Slave select enabled,
// data sampled at the middle of interval,
// clock idle state low,
// data transmitted at low to high edge
SPI1_Init_Advanced(
_SPI_SLAVE_SS_ENABLE,
_SPI_DATA_SAMPLE_MIDDLE,
_SPI_CLK_IDLE_LOW,
_SPI_LOW_2_HIGH
);
Delay_ms(10);
while(1)
{
// cpu health led
LED = ~LED;
// dumy buffer for clock generation
receive_data = SPI1_Read(buffer);
// send received data to portd
PORTD = receive_data;
}
}

Download Files

For download “mikroC PRO for PIC” project and “Proteus 8.0” simulation files, click here.

Comments

Popular posts from this blog

How to Program Parallel Slave Port (PSP) in PIC16F877A

How to Program Interrupts in PIC16F877A