How to Program SPI in PIC16F877A (Master Mode)
The following code demonstrate, how to write a program to use SPI (serial peripheral interface). 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. SPI is very useful feature to easily communicate with other devices like A/D converters, D/A converters and RTC etc. SPI is a synchronous protocol which allows transmission of data from a master device to one or more slave devices and from slave devices to master device over short distances at high frequency (MHz). SPI has the four wire interface:
- SCK (PORTC.3) Serial clock output from master and input to slave [SCK]
- SDI (PORTC.4) Serial data input to master and output from slave [SDO]
- SDO (PORTC.5) Serial data output from master and input to slave [SDI]
- 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;
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;
// set as output
LED_Dir = 0;
SS_Dir = 0;
SCLK_Dir = 0;
SDO_Dir = 0;
// set as input
SDI_Dir = 1;
// Initialize the SPI1 module with default settings
// master mode
// clock Fosc/4
// clock idle state low
// data transimtted on low to high edge
// input data sampled at the middle of interval
SPI1_Init();
Delay_ms(10);
while(1)
{
LED = ~LED;
SS = 0;
SPI1_Write(buffer);
SS = 1;
buffer++;
Delay_ms(500);
}
}
{
unsigned short buffer = 0x00;
// set as output
LED_Dir = 0;
SS_Dir = 0;
SCLK_Dir = 0;
SDO_Dir = 0;
// set as input
SDI_Dir = 1;
// Initialize the SPI1 module with default settings
// master mode
// clock Fosc/4
// clock idle state low
// data transimtted on low to high edge
// input data sampled at the middle of interval
SPI1_Init();
Delay_ms(10);
while(1)
{
LED = ~LED;
SS = 0;
SPI1_Write(buffer);
SS = 1;
buffer++;
Delay_ms(500);
}
}
Download Files
For download “mikroC PRO for PIC” project and “Proteus 8.0” simulation files, click here.
Comments
Post a Comment